Using SetValidator isn't working when using the Testing extensions

Jul 14 at 4:41 AM
Hi Jeremy / anyone else


I'm trying to test A poco that reuses another POCO (like how your example's re-use an Address object / AddressValidator).

When I try and test this Validator using the test Extension Method(s), I'm -expecting- an error, but I do not get one :(

If I just call Validate on the Validator directly, I do get the error messages (which prooves that the Validation has been setup correctly).

Could anyone please help me out?

Here's some snippets from the gist.

public void GivenANegativeValue_Validate_ShouldHaveAValidationError()
    var landDetails = new LandDetails
        Area = new UnitOfMeasure
            Value = -111

    var validator = new LandValidator();
    validator.ShouldHaveChildValidator(land => land.Area, typeof(UnitOfMeasureValidator));

    // This line of code SHOULD pass, but it doesn't because the validation doesn't error.
    validator.ShouldHaveValidationErrorFor(land => land.Area, landDetails.Area);

    // This works....
    var results = validator.Validate(landDetails);
    Assert.Equal(1, results.Errors.Count);
Ok - so I'm testing to make sure i've setup the validator. K, fine .. that works.

Next i'm testing a -property- .. which is Area property. I'm also passing in a bad decimal number so the validator should complain and say that's an error.

The code error there .. but it should pass - notice how I've said: Should-HAVE-AnError...

Anyways .. if you comment out that line and run the entire test, it will pass!


Jul 18 at 7:21 AM
Edited Jul 18 at 7:22 AM

The test extensions only test against rules that are directly defined on the validator directly, not on child validators. So in the test for the LandDetails validator, you should just be testing for the presence of the child validator (using ShouldHaveChildValidator), but to perform assertions against the UnitOfMeasure validator, you'll need to instantiate it separately (preferably in a separate test), and then use ShouldHaveValidationError against this validator instance, not against the LandDetailsValidator.

Jul 18 at 12:16 PM
Ok, got it now. It sounds like a case of Separation of Concerns, which I was abusing.