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);
}
答案 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);
}