我目前正在尝试测试使用TryUpdateModel()的插入方法。我正在伪装控制器上下文,这是必要的,虽然这样做似乎没有发布我已经设置的模型。
以下是我正在测试的方法:
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult _SaveAjaxEditing(int? id)
{
if (id == null)
{
Product product = new Product();
if (TryUpdateModel(product))
{
//The model is valid - insert the product.
productsRepository.Insert(product);// AddToProducts(product);
}
}
else
{
var recordToUpdate = productsRepository.Products.First(m => m.ProductID == id);
TryUpdateModel(recordToUpdate);
}
productsRepository.Save();
return View(new GridModel(productsRepository.Products.ToList()));
}
这是我目前的测试:
[TestMethod]
public void HomeControllerInsert_ValidProduct_CallsInsertForProducts()
{
//Arrange
InitaliseRepository();
var httpContext = CustomMockHelpers.FakeHttpContext();
var context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
controller.ControllerContext = context;
//controller.ControllerContext = new ControllerContext();
var request = Mock.Get(controller.Request);
request.Setup(r => r.Form).Returns(delegate()
{
var prod = new NameValueCollection
{
{"ProductID", "9999"},
{"Name", "Product Test"},
{"Price", "1234"},
{"SubCatID", "2"}
};
return prod;
});
// Act: ... when the user tries to delete that product
controller._SaveAjaxEditing(null);
//Assert
_mockProductsRepository.Verify(x => x.Insert(It.IsAny<Product>()));
}
正在调用该方法但是当它到达TryUpdateModel()时,它似乎无法拾取已发布的对象。关于我出错的地方的任何指示都会很棒。
答案 0 :(得分:6)
对它进行排序。似乎嘲弄Httpcontext完全是过度的。
controller.ControllerContext = new ControllerContext();
var prod = new FormCollection
{
{"ProductID", "1"},
{"Name", "Product Test"},
{"Price", "1234"},
{"SubCatID", "2"}
};
controller.ValueProvider = prod.ToValueProvider();
这就是诀窍。它现在已发布。