[英]Can I use Moq's SetupSequence to throw exception then return void?
I am trying to set up Moq to throw an exception on the first invocation and then return void on the second invocation.我试图设置 Moq 在第一次调用时抛出异常,然后在第二次调用时返回 void。 The method I'm mocking has a
void
return type (eg public void Bar()
).我嘲笑的方法有一个
void
返回类型(例如public void Bar()
)。
Things I have tried我尝试过的事情
This has compile errors because Returns
requires an argument and SetupSequence
requires type arguments.这有编译错误,因为
Returns
需要一个参数,而SetupSequence
需要类型参数。
_mock.SetupSequence(m => m.Bar())
.Throws<Exception>()
.Returns();
This has a compile error because Void
is not a type in C#.这有一个编译错误,因为
Void
不是 C# 中的类型。
_mock.SetupSequence<IMyMock, Void>(m => m.Bar())
.Throws<Exception>() // first invocation throws exception
.CallBase();
Workaround解决方法
In the end I gave up on SetupSequence()
and switched to Callback()
to throw an exception.最后我放弃了
SetupSequence()
并切换到Callback()
抛出异常。
var firstTime = true;
_mock.Setup(m => m.Bar())
.Callback(() =>
{
if (firstTime)
{
firstTime = false;
throw new Exception();
}
});
Question问题
SetupSequence
takes a Func
, not an Action
. SetupSequence
采用Func
,而不是Action
。 Am I correct in assuming that this means SetupSequence()
cannot be used to mock void methods?我是否正确假设这意味着
SetupSequence()
不能用于模拟 void 方法?
You can do this starting with Moq 4.8.0:您可以从 Moq 4.8.0 开始执行此操作:
SetupSequence
support for void
methods was discussed in GitHub issue #451
and added with GitHub pull request #463
.在 GitHub 问题
#451
讨论了对void
方法的SetupSequence
支持,并添加了 GitHub pull request #463
。
You're probably looking for the new .Pass()
method:您可能正在寻找新的
.Pass()
方法:
mock.SetupSequence(m => m.VoidMethod())
.Throws(new InvalidOperationException())
.Pass()
.Pass()
.Throws(new InvalidOperationException())
.Pass();
Note that trailing calls to .Pass()
are probably unnecessary.请注意,对
.Pass()
尾随调用可能是不必要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.