如何用PowerMockito 测试静态方法

本文介绍了如何利用PowerMockito框架进行静态方法的测试。通过@RunWith(PowerMockRunner.class)和@PrepareForTest({DemoStatic.class})注解,可以为静态方法的测试做准备。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假如有下面一个类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
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值