我有以下课程
public class PasswordValidator : AbstractValidator<PasswordContainer>
{
public PasswordValidator()
{
SimpleValidations();
}
private void SimpleValidations()
{
RuleFor(x => x.Password.Length).GreaterThanOrEqualTo(8).WithMessage("Password too short.");
RuleFor(x => x.Password.Length).LessThanOrEqualTo(255).WithMessage("Password too long.");
}
}
PasswordContainer
看起来像这样
public class PasswordContainer
{
public PasswordContainer()
{
}
public string Password { get; set; }
}
现在,当我运行它并使用它验证输入的密码时,它都按预期工作。但是,当我创建单元测试时,它失败了
[Test]
public void Validate_WhenPasswordTooShort_ShouldReturnError()
{
var subject = fixture.Create<PasswordValidator>();
subject.ShouldHaveValidationErrorFor(b => b.Password, new PasswordContainer() { Password = "pass" });
}
此测试不起作用。我收到错误说
“预计属性密码验证错误”
为什么这不起作用?
答案 0 :(得分:1)
在设置规则时,您应该像在测试中一样指定相同的表达式。 GreaterThanOrEqualTo
可能最适合数字属性。
请改为尝试:
RuleFor(x => x.Password)
.Length(8, 255)
.WithMessage("Password should be between 8 and 255 characters.")