-3

I have a property like the following:

    RuleFor(c => c.foo).GreaterThan(0);

In the docs of fluent validation, they specify that if I cannot make use of "ShouldHaveValidationErrorFor" method, I could make some assertions with the "Validate" method, but I can't wrap my head around this

All I got is something along this lines:

    public void Should_Have_Error_When_Foo_Isnt_Greater_Than_Zero()
    {
        var bar = new Bar
        {
            Foo = -1
        };

        var result = validator.TestValidate(bar);

        //Assert.True(bar.Foo > 0, ??)
    }
Rod Ramírez
  • 1,138
  • 11
  • 22

1 Answers1

1

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);
    }
}
rgvlee
  • 2,773
  • 1
  • 13
  • 20