Reputation: 133
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
Reputation: 247163
Callbacks for void calls
Returns()
can be used to get callbacks for members that return a value, but forvoid
members we need a different technique, because we can’t call a method on avoid
return. For these cases we can use theWhen..Do
syntax.Callback builder for more complex callbacks
The
Callback
builder lets us create more complexDo()
scenarios. We can useCallback.First()
followed byThen()
,ThenThrow()
andThenKeepDoing()
to build chains of callbacks. We can also useAlways()
andAlwaysThrow()
to specify callbacks called every time. Note that a callback set by anAlways()
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