2014-10-03 40 views
2

我試圖驗證一個函數的調用不會導致與模擬的任何交互。但是,該模擬在調用該函數之前,在類的構造函數。如何驗證從某個特定時刻開始,與模擬之間沒有更多的互動?

這是不行的,因爲有與模擬互動:

SomeMock someMock = mock(SomeMock.class); 
Subject subject = new Subject(someMock); // interactions with someMock happen here 

subject.doNothingWithMock(); 

verifyNoMoreInteractions(someMock); 

這是一個脆弱的解決方案:

SomeMock someMock = mock(SomeMock.class); 
Subject subject = new Subject(someMock); // interactions with someMock happen here 

verify(someMock).anInteraction(); 
verify(someMock).anotherInteraction(); 

subject.doNothingWithMock(); 

verifyNoMoreInteractions(someMock); 

它的脆弱,因爲如果構造變化有其他與模擬的交互,即使測試不測試構造函數,也需要更改測試。

是否有替代方案?

回答

2

當Mockito靜態導入時,您可以重置模擬:Mockito.reset(someMock);或只是reset(someMock);

這種方法需要可變數量的參數,所以你甚至可以做reset(someMock1, someMock2, ...);

相關問題