문제

I have the following class

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 looks like this

public class PasswordContainer
    {
        public PasswordContainer()
        {
        }

        public string Password { get; set; }
    }

Now, when I run this and use it for validating an entered password it all works as expected. But, when I create a unit test it fails

[Test]
        public void Validate_WhenPasswordTooShort_ShouldReturnError()
        {
            var subject = fixture.Create<PasswordValidator>();
            subject.ShouldHaveValidationErrorFor(b => b.Password, new PasswordContainer() { Password = "pass" });
        }

This test does not work. I get an error saying

"Expected a validation error for property Password"

Why is this not working?

도움이 되었습니까?

해결책

You should probably specify the same expression when setting up the rules as you do in your tests. GreaterThanOrEqualTo probably works best on numeric properties.

Try this instead:

RuleFor(x => x.Password)
.Length(8, 255)
.WithMessage("Password should be between 8 and 255 characters.")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top