使用PowerMock来mock静态方法

使用

引入依赖

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito2</artifactId>
    <version>2.0.9</version>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>2.0.2</version>
</dependency>

代码实现

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({TestPowerMock.PersonUtil.class})
public class TestPowerMock {

    @Test
    public void testCheckParam() throws Exception {
        PowerMockito.mockStatic(PersonUtil.class);
        Mockito.when(PersonUtil.checkParam()).thenReturn(true);
        boolean result = PersonUtil.checkParam();
        System.out.println(result);
    }


    static class PersonUtil {
        public static boolean checkParam() {
            throw new RuntimeException("check error");
        }
    }
}

总结

  1. 使用了powermock,会代替 mockito 本身的模拟静态方法的实现,就不能使用 Mockito.mockStatic() 这种方式了。

  2. 也不能引入 mockito-inline 的依赖,不然报错

    org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is: class java.lang.Class
    
    at com.imooc.TestPowerMock.testCheckParam(TestPowerMock.java:17)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)
    

    不能引入依赖为

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-inline</artifactId>
        <version>3.8.0</version>
    </dependency>
    

    具体原因为 powermock 扩展了 mockito 的 MockMaker 的实现,如果还引入 mockito-inline 依赖,就会将扩展实现给覆盖。

参考

Mockito简介(转)

posted @ 2024-04-06 09:10  strongmore  阅读(197)  评论(0编辑  收藏  举报