I am looking to write unit tests to validate my controller while ensuring that the bind properties are setup correctly. With the following method structure, how can I ensure that only the valid fields are passed from a unit test?
public ActionResult AddItem([Bind(Include = "ID, Name, Foo, Bar")] ItemViewModel itemData)
{
if (ModelState.IsValid)
{
// Save and redirect
}
// Set Error Messages
// Rebuild object drop downs, etc.
itemData.AllowedFooValues = new List<Foo>();
return View(itemData);
}
Broader Explanation: Many of our models have lists of allowed values that we don't want to send back and forth, so we rebuild them when the (ModelState.IsValid == false). In order to ensure these all work, we want to put unit tests in place to assert that the list was rebuilt, but without clearing the list before calling the method, the test is invalid.
We are using the helper method from this SO answer for ensuring the model is validated, and then our unit test is something like this.
public void MyTest()
{
MyController controller = new MyController();
ActionResult result = controller.AddItem();
Assert.IsNotNull(result);
ViewResult viewResult = result as ViewResult;
Assert.IsNotNull(viewResult);
ItemViewModel itemData = viewResult.Model as ItemViewModel;
Assert.IsNotNull(recipe);
// Validate model, will fail due to null name
controller.ValidateViewModel<ItemViewModel, MyController>(itemData);
// Call controller action
result = controller.AddItem(itemData);
Assert.IsNotNull(result);
viewResult = result as ViewResult;
Assert.IsNotNull(viewResult);
itemData = viewResult.Model as ItemViewModel;
// Ensure list was rebuilt
Assert.IsNotNull(itemData.AllowedFooValues);
}
Any assistance or pointers in the right direction is greatly appreciated.