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?
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);
}
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.