2012-04-26 40 views
0

致以驗證我已經根據下面的文章創建了自己的模型綁定: http://www.howmvcworks.net/OnModelsAndViewModels/TheBeautyThatIsTheModelBinderMVC變化ModelBinder的單元測試

在我的應用程序擴展我的人實體是這樣的:

[MetadataType( typeof運算(PersonMetaData))] 公共局部類Person {}

公共類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創建活動和提供的電子郵件無效,ModelState.Valid場是假的。

現在我喜歡的創建方法創建單元測試:

[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?

謝謝!

回答

0

看看this問題和Darin的答案。這是測試模型活頁夾的方式,可能會幫助你。