如何在ASP.NET MVC 2中单元测试DataAnnotationsModelBinder

时间:2010-01-21 15:16:17

标签: c# asp.net-mvc unit-testing validation

我正在使用ASP.NET MVC 2,其DataAnnotation属性如下所示:

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

2 个答案:

答案 0 :(得分:1)

Brad Wilson有一篇关于DataAnnotations ModelBinder的好文章,包括如何对其进行单元测试:http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html

答案 1 :(得分:0)

我通常通过直接调用System.ComponentModel.DataAnnotations.Validator的facade方法对我的模型验证设置进行单元测试。

我写了一篇关于这个主题的文章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"
    };
    /* ... */
}

我不喜欢信任代码才能正常工作,所以我系统地为我的模型验证代码编写单元测试。但是,我确实相信框架/模型绑定器可以执行验证。 这个单元测试允许我编写信任验证的控制器。