Search code examples
c#unit-testingnunitnsubstitute

NSubstitute: Setup a mocked method to fail on the first call, and succeed on the second


How can I use NSubstitute to mock a method that will throw an exception the first time it is called, then succeed the second time it is called?

I know there is an answer for Moq. But I am using NSubstitute.

I wish there was a way like this:

restClient.GetAsync<FieldResponse>("url").
                .Throws(new Exception("error")) // I want to get exception at first call
                .Returns(Task.FromResult(fakeFieldResponse)); // I want to get a value at second call

Solution

  • The Returns method supports returning multiple values. One of these "returns" can throw an exception.

    The second sample on this page in the official docs describes what you need. Your sample will look similar to this:

    restClient
       .GetAsync<FieldResponse>("url")
       .Returns(x => throw new Exception("error"), x => Task.FromResult(fakeFieldResponse));