I am currently trying to test an insert method that uses TryUpdateModel (). I am faking the controller context, which is necessary, and although this works, it seems that the model I installed is not being published.
Here is the method I'm testing:
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult _SaveAjaxEditing(int? id)
{
if (id == null)
{
Product product = new Product();
if (TryUpdateModel(product))
{
productsRepository.Insert(product);
}
}
else
{
var recordToUpdate = productsRepository.Products.First(m => m.ProductID == id);
TryUpdateModel(recordToUpdate);
}
productsRepository.Save();
return View(new GridModel(productsRepository.Products.ToList()));
}
And here is my current test:
[TestMethod]
public void HomeControllerInsert_ValidProduct_CallsInsertForProducts()
{
InitaliseRepository();
var httpContext = CustomMockHelpers.FakeHttpContext();
var context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
controller.ControllerContext = context;
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;
});
controller._SaveAjaxEditing(null);
_mockProductsRepository.Verify(x => x.Insert(It.IsAny<Product>()));
}
The method is called, but when it gets to TryUpdateModel (), it seems like it cannot find the object sent. Any pointers to where I'm wrong would be great.
Henry source
share