Testing the Patch odata webapi method

↘锁芯ラ 提交于 2019-12-06 07:05:43

问题


I need to test the following Patch method in my odata controller from my test project.

[ValidateModel]
        [AcceptVerbs("PATCH", "MERGE")]
        public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<User> patch)
        {
            var user = await db.Users.FindAsync(key);
            if (user == null)
            {
                return NotFound();
            }

            patch.Patch(user);

            Validate(user);

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                db.Entry(user).Property(p => p.UserType).IsModified = false;
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserExists(key))
                {
                    return NotFound();
                }
                throw;
            }

            return Updated(user);
        }

The code in the test project is as follows. Could someone tell me how do I pass value to the Delta parameter. Currently I am getting compilation errors at line controller.Patch(1, user);.

[TestMethod]
        public void TestPatch()
        {
            // Arrange
            var controller = new UsersController();

            var user = new User();
            user.Id = 1;
            user.Lastname = "Johanson";
            // Act
            controller.Patch(1,  <System.Web.OData.Delta> user);

            // Assert
        }

回答1:


var delta = new Delta<User>(typeof(User));
delta.TrySetPropertyValue("Id", 1);
delta.TrySetPropertyValue("Lastname", "Johanson");

I don't know if there are any helpers to make that easier




回答2:


You can also declare the delta using the dynamic keyword and set the properties directly:

dynamic delta = new Delta<User>();
delta.Id = 1;
delta.Lastname = "Johanson";



回答3:


@yenta's answer is perfectly fine, but if you can, also consider using the nameof (since C# 6.0)

var delta = new Delta<User>(typeof(User));
delta.TrySetPropertyValue(nameof(User.Id), 1);
delta.TrySetPropertyValue(nameof(User.Lastname), "Johanson");


来源:https://stackoverflow.com/questions/24953235/testing-the-patch-odata-webapi-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!