0


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

本文转载自: https://blog.csdn.net/q2878948/article/details/124862699
版权归原作者 花落的速度 所有, 如有侵权,请联系我们删除。

“PowerMockito 踩坑 ClassNotPreparedException”的评论:

还没有评论