I Have been struggling testing my software and eventually found a strange behaviour of powermock.
here is the code failing tests:
import static org.junit.Assert.assertEquals;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
import java.time.LocalDateTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(LocalDateTime.class)
@PowerMockIgnore("javax.management.*")
public class StaticDummyPowermock {
@Test
public void doTest() {
mockStatic(LocalDateTime.class);
when(LocalDateTime.now()).thenReturn(null);
assertEquals(null, LocalDateTime.now());
assertEquals(null, new Object() {
public LocalDateTime run() {
return LocalDateTime.now();
}
}.run());
}
}
First assertion succeed but not the second one. Calling mocked method inside another class uses the real method instead of the stub. Therefore all my tests fails as LocalDateTime.now() is called outside of testClass.
I fixed my problem using another library. This code pass the tests
import static org.junit.Assert.assertEquals;
import java.time.LocalDateTime;
import mockit.Mock;
import mockit.MockUp;
import org.junit.Test;
public class StaticDummy {
@Test
public void doTest() {
new MockUp<LocalDateTime>() {
@Mock
LocalDateTime now() {
return null;
}
};
assertEquals(null, LocalDateTime.now());
assertEquals(null, new Object() {
public LocalDateTime run() {
return LocalDateTime.now();
}
}.run());
}
}
I Hope it helps !
Thomas. Willecomme.