Gab*_*art 14 .net unit-testing moq mocking
在我的单元测试中,我正在使用Moq模拟一个受保护的方法,并且想断言它被调用了一定次数.这个问题描述了早期版本的Moq类似的东西:
//expect that ChildMethod1() will be called once. (it's protected)
testBaseMock.Protected().Expect("ChildMethod1")
.AtMostOnce()
.Verifiable();
...
testBase.Verify();
Run Code Online (Sandbox Code Playgroud)
但这不再有效; 从那时起语法发生了变化,我无法使用Moq 4.x找到新的等价物:
testBaseMock.Protected().Setup("ChildMethod1")
// no AtMostOnce() or related method anymore
.Verifiable();
...
testBase.Verify();
Run Code Online (Sandbox Code Playgroud)
Jef*_*ata 25
在Moq.Protected命名空间中,有一个IProtectedMock接口,它具有将Times作为参数的Verify方法.
编辑 至少从Moq 4.0.10827开始提供此功能.语法示例:
testBaseMock.Protected().Setup("ChildMethod1");
...
testBaseMock.Protected().Verify("ChildMethod1", Times.Once());
Run Code Online (Sandbox Code Playgroud)
Sha*_*tin 11
为了增加Ogata的答案,我们还可以验证带参数的受保护方法:
testBaseMock.Protected().Setup(
"ChildMethod1",
ItExpr.IsAny<string>(),
ItExpr.IsAny<string>());
testBaseMock.Protected().Verify(
"ChildMethod1",
Times.Once(),
ItExpr.IsAny<string>()
ItExpr.IsAny<string>());
Run Code Online (Sandbox Code Playgroud)
例如,那将验证ChildMethod1(string x, string y).
另见:http://www.nudoq.org/#!/Packages/Moq.Testeroids/Moq/IProtectedMock(TMock)/M/Verify
| 归档时间: |
|
| 查看次数: |
6172 次 |
| 最近记录: |