问题
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