2010-01-21 36 views
3

我使用ASP.NET MVC 2 DataAnnotation性能上灑屬性,像這樣:在ASP.NET MVC如何單元測試DataAnnotationsModelBinder 2

public class LogOnViewModel 
{ 
    [Required] 
    public string UserName { get; set; } 

    [Required] 
    public string Password { get; set; } 

    [Required] 
    public string Domain { get; set; } 
} 

我有一個單元測試,檢查當前視圖在驗證失敗時呈現。不過,我手動添加錯誤的ModelState得到它的工作:

[Test] 
    public void TestThatLogOnActionRedirectsToLogOnViewIfValidationFails() 
    { 
     //create a invalid view model 
     var model = new LogOnViewModel {UserName = "jsmith"}; 

     //Can I avoid doing this manually? 
     //populate Model State Errors Collection 
     _accountController.ModelState.AddModelError("FirstName", "First Name Required"); 
     _accountController.ModelState.AddModelError("LastName", "Last Name Required"); 

     var result = _accountController.LogOn(model); 

     result.AssertViewRendered() 
      .ForView(Constants.Views.LogOn) 
      .WithViewData<LogOnViewModel>(); 
    } 

有沒有辦法與ModelBinder的直接或間接地在單元測試互動?例如:

[Test] 
    public void TestThatLogOnActionRedirectsToLogOnViewIfValidationFails() 
    { 
     //create a invalid view model 
     var model = new LogOnViewModel {UserName = "jsmith"}; 

     //validate model 
     //not sure about the api call... 
     var validationResults = new DataAnnotationsModelBinder().Validate(model); 

     _accountController.ModelState.Merge(validationResults); 
     var result = _accountController.LogOn(model); 

     result.AssertViewRendered() 
      .ForView(Constants.Views.LogOn) 
      .WithViewData<LogOnViewModel>(); 
    } 

回答

0

我通常單位通過直接調用System.ComponentModel門面方法測試我的模型驗證設置.DataAnnotations.Validator。

我寫了一篇關於http://timoch.com/blog/2013/06/unit-testing-model-validation-with-mvcs-dataannotations/

我結束了這樣的代碼這一主題的文章(文章顯示模型驗證清潔和可重複使用的單元測試基類)

[Test] 
[TestCaseSource("ValidationRule_Source")] 
public void ValidationRule(ValidateRuleSpec spec) { 
    // Arrange 
    var model = CreateValidPersonModel(); 
    // Apply bad valud 
    model.GetType().GetProperty(spec.MemberName).SetValue(model, spec.BadValue); 

    // Act 
    var validationResults = new List<ValidationResult>(); 
    var success = Validator.TryValidateObject(model, new ValidationContext(model), validationResults, true); 

    // Assert 
    Expect(success, False); 
    Expect(validationResults.Count, EqualTo(1)); 
    Expect(validationResults.SingleOrDefault(r => r.MemberNames.Contains(spec.MemberName)), Not.Null); 
} 

public IEnumerable<ValidateRuleSpec> ValidationRule_Source() { 
    yield return new ValidateRuleSpec() { 
     BadValue = null, 
     MemberName = "FirstName" 
    }; 
    yield return new ValidateRuleSpec() { 
     BadValue = string.Empty, 
     MemberName = "FirstName" 
    }; 
    yield return new ValidateRuleSpec() { 
     BadValue = null, 
     MemberName = "LastName" 
    }; 
    /* ... */ 
} 

我不像信任代碼一樣工作,所以我係統地編寫了我的模型驗證代碼的單元測試。但是,我相信框架/模型聯編程序執行驗證。 這個單元測試允許我編寫控制器,相信驗證是可以的。