单元测试Mvc.Compare属性错误地返回模型isValid = true

时间:2013-09-28 15:15:34

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

在单元测试时,

TryValidateObject似乎无法使用Compare模型验证属性。

我得到ModelState.IsValid = true,当我知道它是false时(单位测试时)。

我有这个示例模型:

public class CompareTestModel
{
    public string Password { get; set; }

    [System.Web.Mvc.Compare(
         "Password",
          ErrorMessage = "The passwords do not match")]
    public string PasswordCompare { get; set; }
}

使用此辅助方法在单元测试时验证模型:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

public static class ModelHelper
{
    public static void ValidateModel(
         this Controller controller,
         object viewModel)
    {
        controller.ModelState.Clear();

        var validationContext = new ValidationContext(viewModel, null, null);
        var validationResults = new List<ValidationResult>();

        Validator.TryValidateObject(
            viewModel,
            validationContext,
            validationResults,
            true);

        foreach (var result in validationResults)
        {
            foreach (var name in result.MemberNames)
            {
                controller.ModelState.AddModelError(name, result.ErrorMessage);
            }
        }
    }
}

我运行这个单元测试:

    [Test]
    public void CompareAttributeTest()
    {
        // arrange
        var model = new CompareTestModel();
        model.Password = "password";
        model.PasswordCompare = "different password";

        AccountController controller = new AccountController();

        // act
        controller.ValidateModel(model);

        // assert
        Assert.IsFalse(controller.ModelState.IsValid);
    }

1 个答案:

答案 0 :(得分:2)

CompareAttribute未填写ValidationResult的类MemberNames属性(请参阅source)。因此,result.MemberNames将为空。

因为不需要使用MemberNames属性(ValidationResult甚至还有constructor,所以您需要更改ValidateModel帮助器来处理这种ValidationResult

foreach (var result in validationResults)
{
    if (result.MemberNames.Any())
    {
        foreach (var name in result.MemberNames)
        {
            controller.ModelState.AddModelError(name, result.ErrorMessage);
        }
    }
    else
        controller.ModelState.AddModelError("", result.ErrorMessage);
}