在 NSubstitute 中构造对 void 方法的调用序列并抛出异常
construct sequence of calls to void method with thrown exceptions in NSubstitute
我有一个正在模拟的界面
public interface IFoo {
void Bar(IEnumerable<int>);
}
我的测试代码按顺序调用了 Bar() 几次。我想定义我的单元测试,以便 Bar 在调用它的第 2 次(或第 N 次)时抛出异常。有简洁的方法吗?我找到了一个非空方法的例子: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.
因此,对于您的场景,您可以像这样设置替代品
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
);
我有一个正在模拟的界面
public interface IFoo {
void Bar(IEnumerable<int>);
}
我的测试代码按顺序调用了 Bar() 几次。我想定义我的单元测试,以便 Bar 在调用它的第 2 次(或第 N 次)时抛出异常。有简洁的方法吗?我找到了一个非空方法的例子: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 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.
因此,对于您的场景,您可以像这样设置替代品
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
);