You can do it both ways.
Based on the information provided, assuming your Bar
class and BarValidator
look something like the following:
public class Bar
{
public int Foo { get; set; }
}
public class BarValidator : AbstractValidator<Bar>
{
public BarValidator()
{
RuleFor(c => c.Foo).GreaterThan(0);
}
}
...I'd normally just do it against the validator, it's neater. The following code tests both a pass and fail state.
public class BarValidatorTests
{
[Test]
public void Foo_Zero_HasValidationError()
{
var validator = new BarValidator();
var dto = new Bar { Foo = 0 };
validator.ShouldHaveValidationErrorFor(x => x.Foo, dto);
}
[Test]
public void Foo_One_DoesNotHaveValidationError()
{
var validator = new BarValidator();
var dto = new Bar { Foo = 1 };
validator.ShouldNotHaveValidationErrorFor(x => x.Foo, dto);
}
}
If you do want to use the TestValidate
method, and there are cases where you do want to do it (I use it when my class has a collection of child objects, and I want to test a validation rule on a specific child object), then then following is functionally equivalent to the previous:
public class BarValidatorTestsUsingTestValidate
{
[Test]
public void Foo_Zero_HasValidationError()
{
var validator = new BarValidator();
var dto = new Bar { Foo = 0 };
var validationResults = validator.TestValidate(dto);
validationResults.ShouldHaveValidationErrorFor(x => x.Foo);
}
[Test]
public void Foo_One_DoesNotHaveValidationError()
{
var validator = new BarValidator();
var dto = new Bar { Foo = 1 };
var validationResults = validator.TestValidate(dto);
validationResults.ShouldNotHaveValidationErrorFor(x => x.Foo);
}
}