我有以下测试代码。
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 次。第一个错误是有问题的。
或者在这种情况下,Moq 根本就不是线程安全的?
编辑:这只是测试的一部分,应该不是问题所在,我已经删除了我实际测试的内容,并留下了产生错误的内容。
最佳答案
关于c# - 使用 Moq 测试多线程情况会抛出奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15681053/