我有以下测试代码。
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.
我相信这是起订量的问题。还是我的代码有问题?
如果我等待倒计时事件 5 次,它应该被调用 5 次,而不是 4 次。第一个错误是病态的。
或者在这种情况下起订量根本不是线程安全的?
编辑:这只是测试的一部分,据说不是问题,我已经删除了我实际测试的内容,并留下了产生错误的内容。