使用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);
    }
}
1
2
3
4
5
6
7
测试方法使用到的静态方法
他返回字符串本身,我们将通过Mockito改变他的返回值

    public static String getString(String s) {
        return s;
    }
1
2
3
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);
        }
            }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
总结
带参数的静态方法的Mocktio.mockStatic使用方法

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

    try (MockedStatic<需要模拟的静态方法的类名> mb = Mockito
            .mockStatic(需要模拟的静态方法的类名)) {
        mb.when(需要模拟的静态方法的类名::方法名).thenReturn(返回值);
        //注意:调用待测试方法的时候一定要在try里面写
    }
1
2
3
4
5
常见的错误:
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>
————————————————
版权声明:本文为CSDN博主「摆烂熊猫」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38646452/article/details/124943944

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值