我有一些麻煩使用Moq。單元測試之後會拋出異常,即使將調用相應的方法。Moq驗證方法失敗,即使方法將被稱爲
[TestMethod]
public void CreateFinishTest() {
// mock methods
factoryMock.Setup(f => f.LoadPlan("TestPlanDoNotUse")).Returns(testPlan).Verifiable();
factoryMock.Setup(f => f.CreateFinish(It.IsAny<CreateFinishMessage>(), It.IsAny<string>())).Returns(testFinish.Id).Verifiable();
try {
var cfm = new CreateFinishMessage() {
ClientId = 11,
MessageId = 23456,
CustomerId = 6,
FinishName = "MyFinish",
PlanId = "TestPlanDoNotUse"
};
var cmd = sysCfg.Executor.CreateFinish(cfm); // calls LoadPlan with cfm.PlanId and CreateFinish with cfm and cfm.PlanId
sysCfg.Executor.Execute(cmd);
factoryMock.Verify(f => f.LoadPlan("TestPlanDoNotUse"), Times.Exactly(1));
factoryMock.Verify(f => f.CreateFinish(It.IsAny<CreateFinishMessage>(), It.IsAny<string>()), Times.Exactly(1));
} catch (Exception exc) {
Assert.Fail(exc.Message);
}
}
會出現此錯誤:
Expected invocation on the mock exactly 1 times, but was 0 times: f => f.LoadPlan("TestPlanDoNotUse")
Configured setups:
f => f.LoadPlan("TestPlanDoNotUse"), Times.Once
Performed invocations:
IFactory.LoadPlan("TestPlanDoNotUse")
Factory.CreateFinish(IndiValue.LiveMarket.IndiCore.Communication.MessagingFormat.CreateFinishMessage, "MyFinish")
我試過幾個不同的驗證的調用,但它不會工作。發生的錯誤似乎很混亂,它說LoadPlan("TestPlanDoNotUse")
從來沒有被調用過,但它列出@ Performed invocations。
問題解決了:
我想我找到了問題,它不是一個起訂量的問題。在sysCfg.Executor.CreateFinish(cfm)
中創建並啓動了一個新線程。此線程尚未完成,因此factoryMock.Verify(...)
失敗。
我用AutoResetEvents:
// create AutoResetEvent triggers
AutoResetEvent m_testTrigger1 = new AutoResetEvent(false);
// mock methods
factoryMock.Setup(f => f.LoadPlan(It.IsAny<string>())).Returns(testPlan).Callback(() => m_testTrigger1.Set());
// do something
// wait for triggers
bool didReturn1 = m_testTrigger1.WaitOne(timeOut);
我使用了AutoResetEvents: – Robar 2011-06-27 06:29:58