为什么我的单元测试在独立运行时通过,但在运行多个测试时失败?
当我执行单个单元测试时,我的测试将成功模拟并返回预期结果。但是,当我运行所有单元测试时,我之前通过的测试将失败。
一次试运行
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;
}
}
我找到了适合我们项目的解决方案。我编写了一个 Logger 类,它调用 Android 的内部静态 Log 方法。我的一些测试并没有直接测试Log类。当我忽略所有这些时,基于 powermockito 的测试变成了绿色。但是当运行这些其他测试时,基于 powermockito 的测试将会失败。有时。
这种方法会失败(不稳定):
@RunWith(PowerMockRunner.class)
@PrepareForTest({Log.class}) // WARNING: HERE BE DRAGONS!
public class MyTest {
@Test
public void testMethodThatDoesNotUseStatics() {
// ...
}
@Test
public void usesStatics() {
// ...
}
}
然后我发现你可以用注释每个测试方法@PrepareForTest
, 像这样:
@RunWith(PowerMockRunner.class)
public class MyTest {
@Test
public void testMethodThatDoesNotUseStatics() {
// ...
}
@Test
@PrepareForTest({Log.class}) // that's the way :)
public void usesStatics() {
// ...
}
}
现在测试又恢复正常了。非常好的测试! :)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)