@RunWith(PowerMockRunner.class)@PrepareForTest({DemoStatic.class})public class DemoStaticTest {
}
注意在类的前面要加这个annotation: @PrepareForTest({DemoStatic.class})其次,需要在你的项目中加入下面的maven依赖:
<dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>1.4.10</version> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>1.4.10</version> </dependency>
Mock 无参数的静态方法@Test public void testMockSayHello() { PowerMockito.spy(DemoStatic.class); PowerMockito.when(DemoStatic.sayHello()).thenReturn("my hello"); System.out.println(DemoStatic.sayHello()); // my hello }
Mock 带参数的静态方法@Test public void testSaySomething() throws Exception { PowerMockito.spy(DemoStatic.class); PowerMockito.when(DemoStatic.class, "saySomething", Mockito.anyString()).thenReturn("something to say!"); System.out.println(DemoStatic.saySomething("say hello")); //something to say! }
Mock private 静态方法@Test public void testMockPrivate() throws Exception { PowerMockito.spy(DemoStatic.class); PowerMockito.when(DemoStatic.class, "getMyWord").thenReturn("Nothing to say"); DemoStatic.sayAgain(); //Nothing to say }