简体   繁体   中英

C# Mock dependend validators with FluentValidator

I have a validator like this:

RuleFor(a => a.Id)
    .IsRequired()
    .MustBeValidId()
    .MustExistInDatabase<Command, ChangeRequest>(context)
    .DependentRules(() =>
    {
         RuleFor(a => a.Description)
            .IsRequired()

         ...
    });

I want to test the Description property, which is evaluated only if the Id property is valid.

But for testing purposes, this wouldn't be necessary.

This test should pass:

GetValidator().ShouldNotHaveValidationErrorFor(command => command.Description, "my description");

But it fails because the Id property fails to validate.

To test it, I would have to create an InMemory EFCore provider create the entity to check if it exists in database and then the Description validator would not fail.

Is there any way to mock the Id validator so I could easily test the dependant rules?

The FV unit testing extensions end up running a validate under the covers. Could you mock parts of the validator; probably. But I wouldn't do it in this case. The SUT should be the real deal and you should mock the dependencies (the db context).

I am assuming that the line .MustExistInDatabase<Command, ChangeRequest>(context) is the problem; what does that extension look like? It is possible to mock parts of a db context if you don't want to spin up/seed an in-memory db context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM