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