I do not understand why PowerMock do it this way.
Test-Class
public class Testimpl {
    public long test() {
        long a = System.currentTimeMillis();
        System.out.println("2: " + a);
        return a;
    }
}
jUnit-Class
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(System.class)
public class TestimplTest {
    @InjectMocks
    Testimpl testimpl;
    @Before
    public void setUp() throws Exception {
        initMocks(testimpl);
        PowerMockito.mockStatic(System.class);
    }
    @Test
    public void test() {
        PowerMockito.when(System.currentTimeMillis()).thenReturn(12345l);
        System.out.println("1: " + System.currentTimeMillis());
        long a = testimpl.test();
        System.out.println("3: " + a);
    }
}
Output:
1: 12345
2: 1422547577101
3: 1422547577101
Why this works PowerMock/Mockito correctly in the jUnit TestimplTest class and not in the tested Testimpl class?
I use jUnit 4.11 and Mockito 1.9.5 with PowerMock 1.6.1.
Thank you for your Help.
The annotation @PrepareForTest must have your tested class to correctly mock the System.currentTimeMillis() method. Source and more information on that: PowerMock wiki
With the correct class in @PrepareForTest annotation: @PrepareForTest(Testimpl.class), I have the expected output:
1: 12345
2: 12345
3: 12345
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With