Pure.Krome
Pure.Krome

Reputation: 86957

Validating a simple .NET collection is failing when it should pass

I'm trying to create a FluentValidation rule that tests that my IList<string> has to contain 1 or more items.

Therefore:

Using FluentValidation, I've setup a rule and then a unit test. The unit test fails. I thought that .NotEmpty() will check to see those 3 checks (above)?

Can someone please explain which assumption I made (with respect to F.V.) I have wrong?

Show me da codez

public class AgentValidator : AbstractValidator<Agent>
{
    public AgentValidator()
    {
        RuleFor(agent => agent.Name).NotEmpty()
            .WithMessage("A name is required. eg. Jane Smith.");

        RuleFor(agent => agent.AgencyIds).NotEmpty()
            .WithMessage("At least one AgencyId is requires where this Agent works at.");
    }
}

and the test.

[Fact]
public void GivenNoAgencyIds_Validate_ShouldHaveAnError()
{
    // Arrange.
    var agencyIds = new string[]{}; // No Agency Id's.

    // Act & Assert.
    _agentValidator.ShouldNotHaveValidationErrorFor(agent => agent.AgencyIds, agencyIds);
}

And finally, the error message

FluentValidation.TestHelper.ValidationTestExceptionExpected no validation errors for property AgencyIds at FluentValidation.TestHelper.ValidatorTester`2.ValidateNoError(T instanceToValidate) in c:\Projects\FluentValidation\src\FluentValidation\TestHelper\ValidatorTester.cs: line 40

Upvotes: 0

Views: 269

Answers (1)

Breealzibub
Breealzibub

Reputation: 8095

I think you're using the wrong testing method:

_agentValidator.ShouldNotHaveValidationErrorFor(...)

ShouldNotHaveValidationErrorFor ensures that an error does not exist. But you WANT an error to exist! The function you want would be ShouldHaveValidationErrorFor.

Upvotes: 1

Related Questions