junit 重新加载类
我使用 powermock 来模拟 Logger.getInstance() 方法。这会导致问题,因为 junit 似乎不会重新加载类,并且在第一个测试后测试类具有错误的记录器实例。
public class LoggedClass {
public static Logger log = Logger.getInstance();
....
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({ LoggedClass.class, Logger.class })
public class SomeTests {
private Logger log;
@Before
public void setUp() {
PowerMockito.mockStatic(Logger.class);
log = PowerMockito.mock(Logger.class);
PowerMockito.when(Logger.getInstance()).thenReturn(log);
PowerMockito.mockStatic(LoggedClass.class);
}
@Test
public void firstTest() {
assertTrue(LoggedClass.log == log);
}
@Test
public void secondTest() { // fails
assertTrue(LoggedClass.log == log);
}
}
由于 LoggedClass 具有过时的日志实例,测试失败。我可以显式注入新的记录器实例,但是当有很多静态变量需要模拟时,这很麻烦。
如何设置 junit 在每次运行新测试时重新加载类?
I use powermock to mock Logger.getInstance() method. This causes a problem as junit seems not to reload classes and after the first test test class has wrong logger instance.
public class LoggedClass {
public static Logger log = Logger.getInstance();
....
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({ LoggedClass.class, Logger.class })
public class SomeTests {
private Logger log;
@Before
public void setUp() {
PowerMockito.mockStatic(Logger.class);
log = PowerMockito.mock(Logger.class);
PowerMockito.when(Logger.getInstance()).thenReturn(log);
PowerMockito.mockStatic(LoggedClass.class);
}
@Test
public void firstTest() {
assertTrue(LoggedClass.log == log);
}
@Test
public void secondTest() { // fails
assertTrue(LoggedClass.log == log);
}
}
Test fails as LoggedClass has outdated log instance. I could inject explicitly new logger instance, but that is cumbersome when there are lots of static variables that needs to be mocked.
How can I set junit to reload classes every time it runs new test?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第二个测试失败的原因是您在每个测试的
@Before
方法中创建了一个新的log
实例,但自从调用了Logger.getInstance( )
是静态
,它只发生一次。考虑在@BeforeClass
中执行@Before
中的操作。似乎没有理由为每个测试创建一个新的
log
实例。它是一个mock
,因此只需重置即可。The reason the second test fails is that you are creating a new instance of
log
in your@Before
method for each test but since the call toLogger.getInstance()
isstatic
it is only happening once. Consider doing what you have in@Before
in a@BeforeClass
.There does not seem to be a reason to create a new instance of
log
for each test. It is amock
and can therefore just be reset.