MVC改变ModelBinder单元测试

时间:2012-04-26 13:58:17

标签: unit-testing data-annotations

扩展我的验证我已根据以下文章创建了自己的模型绑定器: http://www.howmvcworks.net/OnModelsAndViewModels/TheBeautyThatIsTheModelBinder

在我的应用程序中,我像这样扩展我的Person实体:

  

[MetadataType(typeof(PersonMetaData))]   公共部分类人员{}

     

public class PersonMetaData {       [CustomRegularExpression(@“(\ w |。)+ @(\ w |。)+”,ErrorMessage =“电子邮件无效”)]   公共字符串名称;   }

我的global.asax看起来像这样:

        protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        //Change default modelbinding
        ModelBinders.Binders.DefaultBinder = new CustomModelBinder();

    }

当我为PersonController调用create事件并且提供的电子邮件无效时,ModelState.Valid字段为false。

现在我想为create方法创建一个单元测试:

    [TestInitialize()]
    public void MyTestInitialize()
    {

        RegisterRoutes(RouteTable.Routes);

        //Change default modelbinding
        ModelBinders.Binders.DefaultBinder = new CustomModelBinder();

    }
    /// <summary>
    ///A test for Create
    ///</summary>
    // TODO: Ensure that the UrlToTest attribute specifies a URL to an ASP.NET page (for example,
    // http://.../Default.aspx). This is necessary for the unit test to be executed on the web server,
    // whether you are testing a page, web service, or a WCF service.
    [TestMethod()]
    public void CreateTest()
    {

        PersonController controller = new PersonController();
        Person Person = new Person();

        Person.Email = "wrognmail.de

            var validationContext = new ValidationContext(Person, null, null);
        var validationResults = new List<ValidationResult>();
        Validator.TryValidateObject(Person, validationContext, validationResults, true);
        foreach (var validationResult in validationResults)
        {
            controller.ModelState.AddModelError(validationResult.MemberNames.First(), validationResult.ErrorMessage);
        }

        ActionResult actual;
        actual = controller.Create(Person);

        // Make sure that our validation found the error!
        Assert.IsTrue(controller.ViewData.ModelState.Count == 1, "err.");
    }

当我调试代码时,ModelState.Valid属性告诉我没有错误。我认为DefaultBinder的注册并不成功。

如何在单元测试中注册我的DefaultBinder?

谢谢!

1 个答案:

答案 0 :(得分:0)

查看this问题和Darin的回答。它是测试模型绑定器的方法,可能会对你有帮助。