Using NSubstitute, how do you mock an exception being thrown in a method returning void?
Let's say our method signature looks something like this:
void Add();
Here's how NSubstitute docs say to mock throwing exceptions for void return types. But this doesn't compile :(
myService
.When(x => x.Add(-2, -2))
.Do(x => { throw new Exception(); });
So how do you accomplish this?
Normally, for synchronous calls, you can just add a . Throws<TException>() after the method you want to mock throwing an exception (or . ThrowsForAnyArgs<TException>() if you don't care about the input arguments).
NSubstitute is a great library for mocking objects for Test Driven Development (TDD) in . NET.
Remove arguments from .Add
method in substitute configuration.
Below sample will compile and work for void method without arguments
var fakeService = Substitute.For<IYourService>();
fakeService.When(fake => fake.Add()).Do(call => { throw new ArgumentException(); });
Action action = () => fakeService.Add();
action.ShouldThrow<ArgumentException>(); // Pass
And same as in documentation shown will compile for void method with arguments
var fakeService = Substitute.For<IYourService>();
fakeService.When(fake => fake.Add(2, 2)).Do(call => { throw new ArgumentException(); });
Action action = () => fakeService.Add(2, 2);
action.ShouldThrow<ArgumentException>(); // Pass
Assumes that interface is
public interface IYourService
{
void Add();
void Add(int first, int second);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With