![](/img/trans.png)
[英]Generic Method for Mock (Moq library) to verify a method was NEVER called with ANY parameter combination
[英]Verify method was called on returned mock
我正在使用Moq對我的工廠進行單元測試,並隨后對其產品執行。
我有一個ParameterAlgorithmFactory
(返回將計算報告參數的算法作為IVisibilityParameterAlgorithm
)和工廠內部的一種方法,分別對這些方法調用Execute()
。
為了對此進行測試,我編寫了如下的單元測試:
//Verfiy that execute is called on all algorithms produced by factory
[TestMethod]
public void ParameterAlgorithmFactory_ReturnedAlgorithm_ExpectExceuteCalled()
{
var mockFactory = new Mock<IParameterAlgorithmFactory>();
var parameterAlgorithm = new Mock<IVisibilityParameterAlgorithm>();
mockFactory.Setup(x => x.Create(LineType.Adjustment)).Returns(parameterAlgorithm.Object);
new ReportParameters().CreateParameters(new DataSet(), mockFactory.Object);
parameterAlgorithm.Verify(x=> x.Execute(new DataSet()));
}
如您所見,我正在從我的模擬工廠返回一個模擬算法( parameterAlgorithm
),然后我想驗證是否已調用Execute()
。
但是我總是得到:
Moq.MockException:預期至少對模擬調用一次,但從未執行過:x => x.Execute(new DataSet())
即使我可以調試並查看正在Execute()
的行。
也許我在工廠做得太多(返回算法並執行),或者我以錯誤的方式使用了Moq?
非常感謝對此測試失敗的原因給予的任何反饋。
正如我在評論中提到的,您應該使用It.IsAny<DataSet>()
而不是new DataSet()
作為驗證參數。
Moq似乎在比較引用而不是“類型”,因此您最終將無法通過驗證。 如果只需要存根參數,則It.IsAny<DataSet>()
恰好應在此處使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.