Cannot Mock<IValidator<Entity>> and ThrowException
See original GitHub issueWhich version of FluentValidation are you using? 9.1.1
Describe the issue that you’re having On previous version I can Mock<IValidator<T>> setup Validate returning ValidationResult with List<ValidationFailure> and test for throwing ValidationError
var validator = new Mock<IValidator<Entity>>();
validator.SetupFail();
// Validator is passed to another class that call
// validator.Validate(instance, options => options.ThrowOnFailures());
await Assert.ThrowsAsync<ValidationException>(() => handler.Handle(request, validator.object));
// Extension method
public static ValidationResult FailResult => new ValidationResult(new List<ValidationFailure>() { new ValidationFailure("Foo", "Bar") });
public static Mock<IValidator<T>> SetupFail<T>(this Mock<IValidator<T>> validator)
{
validator.Setup(p => p.Validate(It.IsAny<T>())).Returns(FailResult).Verifiable();
validator.Setup(p => p.ValidateAsync(It.IsAny<T>(), It.IsAny<CancellationToken>())).ReturnsAsync(FailResult);
validator.Setup(p => p.Validate(It.IsAny<IValidationContext>())).Returns(FailResult).Verifiable();
validator.Setup(p => p.ValidateAsync(It.IsAny<IValidationContext>(), It.IsAny<CancellationToken>())).ReturnsAsync(FailResult);
return validator;
}
Expected Behaviour Throw Exception
Actual Behaviour No Exception is Throw
Note
I looked on source code and I found the code below on AbstractValidator
; question: is still possible to mock IValidator for throwing exception when error ?
protected virtual void RaiseValidationException(ValidationContext<T> context, ValidationResult result) {
throw new ValidationException(result.Errors);
}
A possible solution is to add to IValidationContext
and set public
internal bool ThrowOnFailures { get; set; }
When setup mocking I can select to return errors or raise error.
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
Mockito- Unable to throw exception - java
I throw a new custom exception from method() when an IOException occurs. I tried mocking ByteArrayOutputStream. TestClass test() { ...
Read more >Mocking Exception Throwing using Mockito
Here, we configured an add() method — which returns void — to throw IllegalStateException when called. We can't use when().thenThrow() with the ...
Read more >Throwing exception inside a mock
Hey When throwing an exception inside a mock like mock.method() >> {new Exception()} This is not catched inside the sverice I am testing...
Read more >Throwing Exceptions from Mocked Methods
Use the throwException action to throw an exception from a mocked method. allowing (bank).withdraw(with(any(Money.class))); will(throwException(new ...
Read more >EasyMock - Exception Handling
EasyMock provides the capability to a mock to throw exceptions, so exception handling can be tested. Take a look at the following code...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I’ve pushed out 9.1.2, which makes the getter public on ValidationContext.
Yes, which is why it’s better to have a real validator instance which receives valid/invalid input to trigger a “real” exception. If you mock this, then you can end up in a situation where the mock throws an exception, but the real validator wouldn’t (eg if the
RaiseValidationException
method was overridden, or some other change had been made). By mocking the validator you’re assuming it’ll behave in a particular way when given certain input, but that isn’t necessarily the case, which leads to brittle tests and a false safety net.I will make the getter of that property public on
ValidationContext<T>
(but not the interface), so you can do this if you want to, but I would still highly recommend you take a black-box approach instead. I’ll try and get this done tomorrow.