I am working on asp.net mvc application using the mvc2 framework.
Here is the view.
<% using (Ajax.BeginForm("CreateMenuCategory",
"Admin",
new AjaxOptions { UpdateTargetId = "tabs-MenuCategories", }))
{ %>
<fieldset class="fields">
<legend>
Add Menu Categories
</legend>
<p>
<label for="MenuCategoryName">MenuCategory Name:</label>
<%= Html.TextBox("MenuCategoryName")%>
<%= Html.ValidationMessage("MenuCategoryName")%>
</p>
<p>
<label for="Description">Description</label>
<%= Html.TextBox("Description")%>
<%= Html.ValidationMessage("Description")%>
</p>
<p>
<label for="Notes">Notes</label>
<%= Html.TextBox("Notes")%>
</p>
<p class="submit">
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
Here is the Class I used for modelbinding
public class MenuCategoryBusinessObject
{
//private readonly IMenuRepository _repository;
public int ID { get; set; }
[Required]
[StringLength(20)]
public string MenuCategoryName { get; set; }
[Required]
[StringLength(20)]
public string Description { get; set; }
public string Notes { get; set; }
public IEnumerable<MenuItemBusinessObject> MenuItems
{
get; set;
}
}
And here is my control
[HttpPost]
public ActionResult CreateMenuCategory([Bind(Exclude = "ID")]MenuCategoryBusinessObject menuCategory)
{
if(ModelState.IsValid)
{//if I am valid.
_repository.CreateMenuCategory(menuCategory);
}
IndexMenuCategory model = new IndexMenuCategory
{
MenuCategories = _repository.GetMenuCategories(),
SelectedMenuCategory = null
};
return PartialView("MenuCategories", model);
}
When I do the model binding, the data annotation validation already knows the model is invalid and ModelState.IsValid is false.
However, when I do the unit test, if I feed my own MenuCategoryBusinessObject into the action method, it bypassed the modelbinding, and won't know the ModelState is invalid.
[Fact]
public void CreateNewMenuCategory()
{
// Setup
DataStore dataStore = new DataStore();
IMenuRepository menuRepository = new MenuRepository(dataStore);
MenuCategoryBusinessObject menuCategoryBusinessObject =
new MenuCategoryBusinessObject();
AdminController adminControl = new AdminController(menuRepository);
adminControl.SetFakeControllerContext();
adminControl.Request.SetHttpMethodResult("POST");
// Execute
adminControl.CreateMenuCategory(menuCategoryBusinessObject);
}
So, my questions is, how can effectively unit test in this situation?