我正在編寫一個單元測試類(使用testng)嘲笑成員變量(使用Mockito)並行運行測試。我最初在@BeforeClass方法中設置了預期的模擬,並且在每個測試案例中,我通過爲每個特殊情況創建一個Mockito.when來打破某些情況。並行測試共享模擬
我所看到的(不出所料)是這些測試不是獨立的; Mockito.when在一個測試案例中影響其他人。我注意到我可以在每次測試之前設置模擬,並將@BeforeClass更改爲@BeforeMethod。我仍然沒有想到這些會一直傳遞下去,因爲測試同時仍然在同一個共享模擬對象上運行。但是,所有測試開始始終傳遞。我的問題是「爲什麼」?這最終會失敗嗎?無論我做什麼(Thread.sleep等),我都無法重現失敗。
正在使用@BeforeMethod足以使這些測試獨立嗎?如果是這樣,誰能解釋爲什麼?
如下代碼示例:
public class ExampleTest {
@Mock
private List<String> list;
@BeforeClass // Changing to @BeforeMethod works for some reason
public void setup() throws NoSuchComponentException, ADPRuntimeException {
MockitoAnnotations.initMocks(this);
Mockito.when(list.get(0)).thenReturn("normal");
}
@Test
public void testNormalCase() throws InterruptedException {
assertEquals(list.get(0), "normal"); // Fails with expected [normal] but found [exceptional]
}
@Test
public void testExceptionalCase() throws InterruptedException {
Mockito.when(list.get(0)).thenReturn("exceptional");
assertEquals(list.get(0), "exceptional");
}
}
我明白,'parallel =「測試」'沒有做我認爲正在做的事情。有道理,並感謝有關解決此問題的建議,當我更改爲'parallel =「methods」'! – ChrisV