如何使用Data Annotation验证对ModelBind进行单元测试?

时间:2009-10-31 10:57:37

标签: asp.net-mvc unit-testing asp.net-mvc-2

我正在使用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方法,它会绕过modelbinding,并且不会知道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);
    }

所以,我的问题是,在这种情况下如何有效地进行单元测试?

2 个答案:

答案 0 :(得分:2)

controllerInstance.ModelState.AddModelError("", "Dummy value.");

在调用方法之前添加虚拟值将清除 IsValid 标志。然后只需调用您的操作方法来测试此特定代码路径。

答案 1 :(得分:0)

为了测试模型是否正确地进行数据注释,我可能会在这些行中做一些事情:

[TestMethod]
public void Description_Should_Be_Required()
{
    Expression<Func<MenuCategoryBusinessObject, object>> expression = 
        o => o.Description;
    var me = expression.Body as MemberExpression;
    var att = (RequiredAttribute[])me.Member
              .GetCustomAttributes(typeof(RequiredAttribute), false);
    att.Length.ShouldEqual(1);
}

您需要测试的另一件事是您实际使用DataAnnotationsModelBinder而不是默认值:

ModelBinders.Binders.DefaultBinder = new DataAnnotationsModelBinder();