PowerMockito 踩坑 ClassNotPreparedException

现象

想通过PowerMockito.mockStatic() 对静态方法进行mock,代码如下

import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(StringUtils.class)
@PowerMockIgnore("javax.crypto.*")
public class MyTest {

    @Test
    public void test(){
        PowerMockito.mockStatic(StringUtils.class);
        PowerMockito.when(StringUtils.isEmpty("empty")).thenReturn(true);
        Assertions.assertTrue(StringUtils.isEmpty("empty"));
    }
}

然而报错:

org.powermock.api.mockito.ClassNotPreparedException: 

[Ljava.lang.Object;@4a60ee36
The class org.apache.commons.lang3.StringUtils not prepared for test.

原因

PowerMock(2.2.0-beta)与Junit5不兼容,注意代码中的

import org.junit.jupiter.api.Test;

jupiter为junit5的包。

解决方法

1.升mockito版本并弃用powermock

Mockito在3.4版本以上支持mock静态方法,文档见
mockito文档

2.版本升级很困难难,新增junit4依赖,然后将junit5相关import换为junit4的

import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(StringUtils.class)
@PowerMockIgnore("javax.crypto.*")
public class MyTest {

    @Test
    public void test(){
        PowerMockito.mockStatic(StringUtils.class);
        PowerMockito.when(StringUtils.isEmpty("empty")).thenReturn(true);
        Assertions.assertTrue(StringUtils.isEmpty("empty"));
    }
}
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值