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?
The reason the second test fails is that you are creating a new instance of
login your@Beforemethod for each test but since the call toLogger.getInstance()isstaticit is only happening once. Consider doing what you have in@Beforein a@BeforeClass.There does not seem to be a reason to create a new instance of
logfor each test. It is amockand can therefore just be reset.