如何用PowerMockito 测试静态方法

xiaoxiao2021-02-27  206

假如有下面一个类DemoStatic,它里面定义了各种静态方法,这些静态方法可能是一些Utilities方法,辅助其它的类。 package mock.demo;public class DemoStatic { public static String sayHello() { return "Hello"; } public static String saySomething(String word) { return word; } public static void sayAgain() { System.out.println(getMyWord()); } private static String getMyWord() { return "This is my word"; }}首先,我们写一个测试类DemoStaticTest.java, 如下:

@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 }

转载请注明原文地址: https://www.6miu.com/read-8826.html

最新回复(0)