9

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?

Kavya Shetty
  • 185
  • 2
  • 14

1 Answers1

17

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);
}
Fabio
  • 31,528
  • 4
  • 33
  • 72