0

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
emert117
  • 1,268
  • 2
  • 20
  • 38
  • 2
    NUnit is the assertion framework, not a mocking library. You can't compare Moq & NUnit – itsdaniel0 May 11 '23 at 19:01
  • I think it's helps, please look at https://stackoverflow.com/questions/62640655/mock-a-method-twice-with-nsubstitute-to-first-throw-error-and-later-return-value – Prasad Ramireddy May 11 '23 at 22:00

1 Answers1

1

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));
Yan Sklyarenko
  • 31,557
  • 24
  • 104
  • 139