question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cannot Mock<IValidator<Entity>> and ThrowException

See original GitHub issue

Which 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:closed
  • Created 3 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
JeremySkinnercommented, Aug 12, 2020

I’ve pushed out 9.1.2, which makes the getter public on ValidationContext.

1reaction
JeremySkinnercommented, Aug 11, 2020

in some situation throwing exception by validator is a trigger for other code.

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.

Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found