我有以下测试代码。
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在这种情况下根本不是线程安全的吗?
编辑:这只是测试的一部分,据说这不是问题,我已经删除了我实际测试的内容,并留下了产生错误的内容。