开发者

How to unit test ModelBind with Data Annotation validation?

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);
 开发者_Python百科   }

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?


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

Adding a dummy value before the method is called will clear the IsValid flag. Then just call your action method to test this particular code path.


In order to test if the model is correctly data annotated I would probably do something among the lines:

[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);
}

The other thing you need to test is that you are effectively using the DataAnnotationsModelBinder instead of the default one:

ModelBinders.Binders.DefaultBinder = new DataAnnotationsModelBinder();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜