具有最终类System和静态方法currentTimeMillis的PowerMock

dep*_*rov 4 java methods static final powermock

我不明白为什么PowerMock这样做.

测试类

public class Testimpl {
    public long test() {
        long a = System.currentTimeMillis();
        System.out.println("2: " + a);
        return a;
    }
}
Run Code Online (Sandbox Code Playgroud)

JUnit的级

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

输出:

1:12345

2:1422547577101

3:1422547577101

为什么在jUnit TestimplTest类中正确使用PowerMock/Mockito而不是在经过测试的Testimpl类中?

我使用jUnit 4.11和Mockito 1.9.5与PowerMock 1.6.1.

谢谢您的帮助.

Syl*_*gat 7

注释@PrepareForTest必须使您的测试类正确模拟该System.currentTimeMillis()方法.来源和更多信息:PowerMock wiki

使用@PrepareForTest注释中的正确类:@PrepareForTest(Testimpl.class),我有预期的输出:

1:12345
2:12345
3:12345

  • @TheLion,您是否设法模拟了“System.currentTimeMillis”?我在 https://github.com/powermock/powermock/wiki/PowerMock-Configuration 上读到,默认情况下 PowerMock 使用其 MockClassLoader 加载所有类。类加载器加载并修改除系统类之外的所有类。所以看起来我们不能模拟 Java 静态方法,必须编写包装器。我写了一个,它有效:https://gist.github.com/MaksimDmitriev/202142b6345ae86a3fda7577390fb1bf。而这个 https://gist.github.com/MaksimDmitriev/1ceea5c08abb5fa9dc485fce7f71f630 没有 (2认同)