Question

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?

Était-ce utile?

La solution

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.")
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top