爲什麼我的單元測試在獨立運行時通過,但在運行多個測試時失敗?PowerMock測試通過然後失敗
當我執行單個單元測試時,我的測試將成功模擬並返回預期結果。但是,當我運行所有單元測試時,先前通過的測試將失敗。
一次測試運行
shouldDoThisAgain() - 通過
多重測試運行
shouldDoThis() - 通過
shouldDoThisAgain() - 失敗
shouldDoThisAgainAgain() - 失敗
我的測試:
@PrepareForTest({OtherMethods.class})
@PowerMockIgnore("javax.management.*")
@RunWith(PowerMockRunner.class)
public class DbTest {
@Test
public void shouldDoThis() throws Exception() {
Dal dalMock = mock(Dal.class)
PowerMockito.whenNew(Dal.class).withAnyArguments().thenReturn(dalMock)
List<Result> results = new ArrayList<Result>();
results.add(new Result(1,2,3));
when(dalMock.getResults()).thenReturn(results)
assertTrue(Wrapper.MY_WRAPPER.run());
}
@Test
public void shouldDoThisAgain() throws Exception() {
Dal dalMock = mock(Dal.class)
PowerMockito.whenNew(Dal.class).withAnyArguments().thenReturn(dalMock)
List<Result> results = new ArrayList<Result>();
results.add(new Result(2,3,4));
when(dalMock.getResults()).thenReturn(results)
assertTrue(Wrapper.MY_WRAPPER.run());
}
@Test
public void shouldDoThisAgainAgain() throws Exception() {
Dal dalMock = mock(Dal.class)
PowerMockito.whenNew(Dal.class).withAnyArguments().thenReturn(dalMock)
List<Result> results = new ArrayList<Result>();
results.add(new Result(6,5,3));
when(dalMock.getResults()).thenReturn(results)
assertTrue(Wrapper.MY_WRAPPER.run());
}
}
我的課:
public class Wrapper {
// not Runnable
public static final MyWrapper MY_WRAPPER = new MyWrapper(...){
@Override
public boolean run() {
// returns empty list when the test is alone
// returns 'results' variable when ran with other tests alone
List<Result> results = OtherMethods.getDal().getResults();
return !results.isEmpty()
}
};
}
public class OtherMethods {
private static final Logger LOGGER = LogManager.getLogger(OtherMethods.class);
public static Dal dal;
static Dal getDal() {
if (dal == null) {
try {
dal = new Dal();
} catch (Exception e) {
LOGGER.fatal("DB Connection could not be created for Geonames");
LOGGER.fatal(e);
}
}
return dal;
}
}
你的'OtherMethods'特別是'getDal()'的實現是非常糟糕的主意。 –