使用 Moq 验证受保护方法被调用的次数
在我的单元测试中,我使用 Moq 模拟受保护的方法,并想断言它被调用一定次数。 这个问题描述了早期版本的 Moq 的类似内容:
//expect that ChildMethod1() will be called once. (it's protected)
testBaseMock.Protected().Expect("ChildMethod1")
.AtMostOnce()
.Verifiable();
...
testBase.Verify();
但这不再有效;从那时起,语法发生了变化,我无法使用 Moq 4.x 找到新的等效项:
testBaseMock.Protected().Setup("ChildMethod1")
// no AtMostOnce() or related method anymore
.Verifiable();
...
testBase.Verify();
In my unit-tests I'm mocking a protected method using Moq, and would like to assert that it is called a certain number of times. This question describes something similar for an earlier version of Moq:
//expect that ChildMethod1() will be called once. (it's protected)
testBaseMock.Protected().Expect("ChildMethod1")
.AtMostOnce()
.Verifiable();
...
testBase.Verify();
but this no longer works; the syntax has changed since then and I cannot find the new equivalent using Moq 4.x:
testBaseMock.Protected().Setup("ChildMethod1")
// no AtMostOnce() or related method anymore
.Verifiable();
...
testBase.Verify();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Moq.Protected 命名空间中,有一个IProtectedMock 接口,具有验证方法时间作为参数。
编辑
至少从 Moq 4.0.10827 起可用。语法示例:
In the Moq.Protected namespace, there is an IProtectedMock interface that has a Verify method taking Times as a parameter.
Edit
This is available since at least Moq 4.0.10827. Syntax example:
为了补充 Ogata 的答案,我们还可以验证接受参数的受保护方法:
例如,这将验证
ChildMethod1(string x, string y)
。另请参阅:http://www. nudoq.org/#!/Packages/Moq.Testeroids/Moq/IProtectedMock(TMock)/M/Verify
To augment Ogata's answer, we can also verify a protected method that takes arguments:
For instance, that would verify
ChildMethod1(string x, string y)
.See also: http://www.nudoq.org/#!/Packages/Moq.Testeroids/Moq/IProtectedMock(TMock)/M/Verify