2010-01-21 39 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" 
    }; 
    /* ... */ 
} 

我不像信任代码一样工作,所以我系统地编写了我的模型验证代码的单元测试。但是,我相信框架/模型联编程序执行验证。 这个单元测试允许我编写控制器,相信验证是可以的。