【发布时间】:2018-09-28 04:30:11
【问题描述】:
我有一个在foreach 循环中多次调用的方法,每次都使用相同的参数值。
foreach (var item in myCollection)
{
// do some stuff with item
// then...
var result = _myService.Foo(aConstant, anotherConstant);
// do something with result
}
我正在尝试编写一个测试,以确保循环继续迭代,即使_myService.Foo() 在第一次通过时抛出异常。
在Moq 中,我可以像这样链接对Returns 和Throws 的调用:
mockService.Setup(x => x.Foo(aConstant, anotherConstant)).Throws<Exception>().Returns(someResult);
这将导致对Foo 的调用引发异常,但所有后续调用都将返回someResult。我的主要目标是确保将 try/catch 块包裹在我的 foreach 块内的代码的后半部分,这样即使发生异常,循环也会继续。
foreach (var item in myCollection)
{
// do some stuff with item
// then...
try
{
var result = _myService.Foo(aConstant, anotherConstant);
// do something with result
}
catch (Exception e)
{
// ignore any exceptions here and continue looping
}
}
如何在FakeItEasy 中完成类似的操作?或者有什么不同的(更好的)策略可以用来做这种断言?
【问题讨论】:
标签: c# exception mocking moq fakeiteasy