2013-03-28 36 views
3

我有以下測試代碼。使用Moq測試多線程情況會引發奇怪的錯誤

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在這種情況下根本不是線程安全嗎?

編輯:這只是測試的一部分,應該不是問題,我已經刪除了我實際測試的內容,並留下了產生錯誤的內容。

+0

我認爲你需要在這裏提供更多的代碼。你的checkerMock設置在哪裏? –

+0

+1。我遇到了同樣的*間歇性問題。就我而言,這也是一個涉及多線程的場景 – danielpops

+0

+1然後問題Daniel =) –

回答

0

Moq有一個問題,在moq對象上記錄調用不是線程安全的。我相信這是在某些版本的4.1

現在固定請參閱Issue 249Issue 62