Reputation: 667
I'm doing some unit testing using FluentValidation in Asp.net. I have setup a rule stating that an object is not allowed to be null, as it's going to be used as an argument in a method. The rule is made in a validator-class in the constructor:
//Object itself.
RuleFor(x => x).NotNull();
The unit test looks like (I'm using NUnit):
[Test]
public void RequestObjectIsNull_ExpectError()
{
BusinessRequest request = null;
var result = validator.Validate(request);
Assert.IsFalse(result.IsValid);
}
It fails with the message:
Message: System.ArgumentNullException : Cannot pass null model to Validate. Parameter name: instanceToValidate
How do I test this?
Upvotes: 3
Views: 2549
Reputation: 1547
This question is quite old but I have stumbled upon the same issue. I wanted the fluent validator to validate it for me if it is null and say so and not throw an exception, instead of me explicitly checking for it. I have found a solution of overriding the existing methods, For example:
public class MyValidator : AbstractValidator<MyObject>
{
public MyValidator()
{
RuleSet("MyRule", () =>
{
RuleFor(x=>x.MyProperty=="Something").WithMessage("failed");
});
}
public override Task<ValidationResult> ValidateAsync(ValidationContext<MyObjec>> context, CancellationToken cancellation = default)
{
return context.InstanceToValidate == null ? Task.FromResult(new ValidationResult(new[] { new ValidationFailure("MyObject", "filed with null") })) : base.ValidateAsync(context, cancellation);
}
}
Upvotes: 2