Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSubstitute - mock throwing an exception in method returning void

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?

like image 654
Kavya Shetty Avatar asked Jun 02 '17 09:06

Kavya Shetty


People also ask

How do you throw an exception in NSubstitute?

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).

What is NSubstitute?

NSubstitute is a great library for mocking objects for Test Driven Development (TDD) in . NET.


1 Answers

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);
}
like image 100
Fabio Avatar answered Nov 15 '22 01:11

Fabio