5

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

1 回答 1

2

CompareAttribute不填写的ValidationResultMemberNames属性(参见源代码)。所以你的result.MemberNames将是空的。

因为不需要使用该MemberNames属性(ValidationResult甚至为此有一个构造函数),所以您需要更改您的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);
}
于 2013-09-28T18:38:51.760 回答