我有以下测试代码。
for (int z = 0; z < 1000; z++)
{
....
const int threads = 5;
CountdownEvent ce = new CountdownEvent(threads);
for (int i = 0; i < threads; i++)
{
ThreadPool.QueueUserWorkItem(delegate
{
checkerMock.GetCurrentlyReleasedVersion();
ce.Signal();
});
}
ce.Wait();
mock = Mock.Get(checkerMock);
mock.Verify(a => a.GetCurrentlyReleasedVersion(), Times.Exactly(threads), string.Format("on try {0} failed", z + 1));
}
有时测试可以多次运行良好。它永远不会运行所有
1,000
。有时会引发以下错误:
System.NullReferenceException: Object reference not set to an instance of an object.
at Moq.MethodCall.Matches(ICallContext call)
at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
at System.Linq.Enumerable.Count(IEnumerable`1 source)
at Moq.Mock.VerifyCalls(Interceptor targetInterceptor, MethodCall expected, Expression expression, Times times)
at Moq.Mock.Verify(Mock mock, Expression`1 expression, Times times, String failMessage)
at Moq.Mock`1.Verify(Expression`1 expression, Times times, String failMessage)
等时出现以下错误:
Moq.MockException: on try 14 failed
Expected invocation on the mock exactly 5 times, but was 4 times: a => a.GetCurrentlyReleasedVersion()
No setups configured.
我相信这是Moq的问题。还是我的代码有问题?
如果我等待倒数事件5次,则应调用5次,而不是4次。第一个错误很严重。
还是Moq在这种情况下根本不是线程安全的?
编辑:这只是测试的一部分,应该不是问题,我已经删除了实际测试的内容,并保留了产生错误的内容。
最佳答案
Moq存在一个问题,即在Moq对象上记录调用不是线程安全的。我认为此问题已在4.1的某些版本中修复
请参阅Issue 249和Issue 62
关于c# - 使用Moq测试多线程情况会引发奇怪的错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15681053/