user3805884
user3805884

Reputation: 133

construct sequence of calls to void method with thrown exceptions in NSubstitute

I have an interface I'm mocking out

public interface IFoo {
    void Bar(IEnumerable<int>);
}

My code under test calls Bar() a few times in sequence. I want to define my unit test such that Bar throws an exception the 2nd (or Nth) time it is called. Is there a succinct way to do so? I've found an example for non-void methods: http://nsubstitute.github.io/help/multiple-returns/

Upvotes: 1

Views: 1354

Answers (1)

Nkosi
Nkosi

Reputation: 247163

Callbacks for void calls

Returns() can be used to get callbacks for members that return a value, but for void members we need a different technique, because we can’t call a method on a void return. For these cases we can use the When..Do syntax.

Callback builder for more complex callbacks

The Callback builder lets us create more complex Do() scenarios. We can use Callback.First() followed by Then(), ThenThrow() and ThenKeepDoing() to build chains of callbacks. We can also use Always() and AlwaysThrow() to specify callbacks called every time. Note that a callback set by an Always() method will be called even if other callbacks will throw an exception.

So for your scenario you can setup the substitute like

var foo = Substitute.For<IFoo>();
foo
    .When(_ => _.Bar(Arg.Any<IEnumerable<int>>()))
    .Do(Callback
        .First(_ => _)//First time do nothing
        .ThenThrow(new Exception()) //second time throw the provided exception
    );

Reference Callbacks, void calls and When..Do

Upvotes: 4

Related Questions