Rob*_*bar 6 .net c# unit-testing moq mocking
我使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
发生此错误:
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")
Run Code Online (Sandbox Code Playgroud)
我尝试了几种不同的验证调用,但它不起作用.并且发生的错误看起来很混乱,它说LoadPlan("TestPlanDoNotUse")永远不会被调用,但它列出了@Performed invocations.
问题解决了:
我想我发现了问题,这不是Moq的问题.在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);
Run Code Online (Sandbox Code Playgroud)
在Verifiable未被调用时,期望中的参数与生产代码使用的参数匹配非常重要.
关于Thread.Sleep的使用,尽可能避免使用它,因为它只会减慢测试速度以满足您最慢的机器.我通常会将WaitHandles引入我的测试中,以确保测试的运行速度与代码一样快.
以一个在这里一个小工具偷看使用WaitHandles的事件.
| 归档时间: |
|
| 查看次数: |
4972 次 |
| 最近记录: |