简体   繁体   中英

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM