我正在使用 mvc2 框架开发 asp.net mvc 应用程序。
这是视图。
<% 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>
<% } %>
这是我用于模型绑定的类
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;
}
}
这是我的控制
[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);
}
当我进行模型绑定时,数据注释验证已经知道模型无效并且 ModelState.IsValid 为 false。
但是,当我进行单元测试时,如果我将自己的 MenuCategoryBusinessObject 输入到 action 方法中,它会绕过模型绑定,并且不会知道 ModelState 无效。
[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);
}
所以,我的问题是,在这种情况下如何有效地进行单元测试?