我能够让以下代码在服务器上工作,但不能在单元测试中工作。在单元测试中,简单属性设置正确,但子对象不正确。我已经把头撞在墙上太久了,所以欢迎任何建议。
控制器:
[HttpPost]
public bool Save(int id)
{
var itemFromRepository = this.itemRepository.FetchById(id);
if (itemFromRepository != null)
{
this.TryUpdateModel(
itemFromRepository,
"Item",
new[] {
"AnIntProperty",
"AStringProperty",
"Category.Id"
});
if (itemFromRepository.Category!= null)
{
itemFromRepository.Category= this.categoryRepository.FetchById(itemFromRepository.Category.Id);
}
if (ModelState.IsValid)
{
this.itemRepository.Update(itemFromRepository);
return true;
}
}
return false;
}
单元测试:
this._controller.ControllerContext = new ControllerContext();
Item item = this.items.First();
var updatedCategory = this.categories.Last();
var updatedStringProperty = "Fake Value";
var updatedIntProperty = 4;
var formValues = new FormCollection {
{ "Item.AnIntProperty", updatedStringProperty},
{ "Item.Category.Id", updatedCategory.Id.ToString() },
{ "Item.AStringProperty", updatedIntProperty.ToString() }
};
var result = this._controller
.WithIncomingValues(formValues)
.Save(item.Id);
这通过:
Assert.That(
item.AStringProperty,
Is.EqualTo(updatedStringProperty));
Assert.That(
item.AnIntProperty,
Is.EqualTo(updatedIntProperty));
这不会:
Assert.That(
item.Category,
Is.Not.Null);
Assert.That(
item.Category.Name,
Is.EqualTo(updatedCategory.Name));