0


使用Mockito模拟Static静态方法

前言

Mockito3.4.0版本之后增加了对Static方法的支持,在这里简单记录下Mockito.mockStatic方法的用法

测试代码

这是待测试的方法,用到了TestUtil.getString这个静态方法,将使用Mockito改变他的返回值

public class TestTarget {
    public boolean isEqual(String source) {
        String target = TestUtil.getString(source);
        System.out.println("target is:" + target);
        return source.equals(target);
    }
}

测试方法使用到的静态方法
他返回字符串本身,我们将通过Mockito改变他的返回值

    public static String getString(String s) {
        return s;
    }

Junit测试代码,执行isEqual方法TestUtil.getString(source)返回了target而不是source,最后return false

    @Test
    public void testisEqual() {
        TestTarget testTarget = new TestTarget();
        //方法的输入为source
        String source = "source";
        //通过Mockito模拟对象
        try (MockedStatic<TestUtil> mb = Mockito
                .mockStatic(TestUtil.class)) {
             //模拟带参数的静态方法的返回值
             //方法应该返回输入的source本身,此处通过mockito返回了target
            mb.when(()->TestUtil.getString(source)).thenReturn("target");
            boolean isEqual = testTarget.isEqual(source);
            assertFalse(isEqual);
        }
            }

总结

带参数的静态方法的Mocktio.mockStatic使用方法

    try (MockedStatic<需要模拟的静态方法的类名> mb = Mockito
            .mockStatic(需要模拟的静态方法的类名)) {
        mb.when(()->需要模拟的静态方法的类名.方法名(参数)).thenReturn(返回值);
        //注意:调用待测试方法的时候一定要在try里面写
    }

无参数的静态方法

    try (MockedStatic<需要模拟的静态方法的类名> mb = Mockito
            .mockStatic(需要模拟的静态方法的类名)) {
        mb.when(需要模拟的静态方法的类名::方法名).thenReturn(返回值);
        //注意:调用待测试方法的时候一定要在try里面写
    }

常见的错误:
org.mockito.exceptions.base.MockitoException:
The used MockMaker SubclassByteBuddyMockMaker does not support the creation of static mocks

Mockito’s inline mock maker supports static mocks based on the Instrumentation API.
You can simply enable this mock mode, by placing the ‘mockito-inline’ artifact where you are currently using ‘mockito-core’.

出现该错误是缺少mockito-inline
在pom.xml中引入即可

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <version>4.5.1</version>
    <scope>test</scope>
</dependency>

本文转载自: https://blog.csdn.net/qq_38646452/article/details/124943944
版权归原作者 摆烂熊猫 所有, 如有侵权,请联系我们删除。

“使用Mockito模拟Static静态方法”的评论:

还没有评论