Reputation: 147
I'm trying to unit test a validator I have that checks when 2 fields match - but am at a loss of exactly how to get it done.
I've tried
var validator = new CreateUserValidator();
validator.ShouldHaveValidationErrorFor(user => user.Password.Equals(user.PasswordConfirmation));
But there is no overload for ShouldHaveValidationErrorFor that takes 1 argument. Short of declaring a local variable and setting the value to that of the PasswordConfirmation I'm at a loss how to effectively test this.
Does anyone have any ideas out there?
Upvotes: 1
Views: 1568
Reputation: 6992
Honestly i find that extension is bit confusing, same as the Fluent Validator itself (This is just my opinion) But once you get used to it, the extension and the product is useful.
For your issue, you need
a. First argument to say what field/property the validator has been setup for
b. An object that has the violation/succession of the rule validation.
See the code below.
[TestFixture]
public class Tests
{
[Test]
public void NameEqualTest()
{
var v = new PersonValidator();
var p = new Person() {Name1 = "Name2", Name2 = "Name2"};
//I prefer this..
//ValidationResult validationResult = v.Validate(p);
//Assert.True(validationResult.IsValid);
v.ShouldNotHaveValidationErrorFor(person => p.Name1, p);
}
}
Use ShouldNotHaveValidationErrorFor as it is less confusing.. When 2 properties are equal, test pass. i.e no validation errors.
When 2 properies are not equal, you get an error.
public class Person
{
public string Name1 { get; set; }
public string Name2 { get; set; }
}
public class PersonValidator : AbstractValidator<Person>
{
public PersonValidator()
{
RuleFor(x => x.Name1).Equal(x => x.Name2)
.WithMessage("names are not equal");
}
}
Upvotes: 2