Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerMock with final class System and static Method currentTimeMillis

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.

like image 604
deprov Avatar asked Mar 18 '23 05:03

deprov


1 Answers

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

like image 108
Sylvain Bugat Avatar answered Apr 06 '23 03:04

Sylvain Bugat