問題描述
在我的單元測試中,我正在使用 Moq 模擬一個受保護的方法,并且想斷言它被調用了一定次數.這個問題描述了與早期版本的 Moq 類似的內容:
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();
但這不再有效;從那時起語法發生了變化,我找不到使用 Moq 4.x 的新等效項:
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();
推薦答案
在 Moq.Protected 命名空間,有一個 IProtectedMock 接口,具有以 Times 作為參數的 Verify 方法.
In the Moq.Protected namespace, there is an IProtectedMock interface that has a Verify method taking Times as a parameter.
編輯這至少從最小起訂量 4.0.10827 開始可用.語法示例:
Edit This is available since at least Moq 4.0.10827. Syntax example:
testBaseMock.Protected().Setup("ChildMethod1");
...
testBaseMock.Protected().Verify("ChildMethod1", Times.Once());
這篇關于驗證使用 Moq 調用受保護方法的次數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!