zoukankan      html  css  js  c++  java
  • springboot项目单元测试使用PowerMockito跳过静态方法

    有时候做单元测试经常需要跳过某些工具类,比如工具类对用户登录态的获取和初始化:
    image

    Mockito不支持静态方法的Mock,当所测逻辑里有静态工具类方法或私有方法我们希望他返回特定值时(极值边界、异常测试场景),我们要用到PowerMock去弥补Mockito的不足

    一、使用PowerMock所需要的依赖

            <dependency>
                <groupId>org.powermock</groupId>
                <artifactId>powermock-module-junit4</artifactId>
                <version>1.7.4</version>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>org.powermock</groupId>
                <artifactId>powermock-api-mockito</artifactId>
                <version>1.7.4</version>
                <scope>test</scope>
            </dependency>
    
    

    二、Mock工具类和模拟静态方法

    在测试类上引入注解

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({CommonUtils.class})
    

    Mock工具类

            PowerMockito.mockStatic(CommonUtils.class);
    

    模拟静态方法

            PowerMockito.when(CommonUtils.getCustomerId(any())).thenReturn("staticMock");
            PowerMockito.when(CommonUtils.getCustomerPhone(any())).thenReturn("staticMock");
    

    @PrepareForTest({静态方法类名.class})注解不能漏,漏了这个会报下面的错误

    org.powermock.api.mockito.ClassNotPreparedException:
    
  • 相关阅读:
    解决GitHub下载速度缓慢的问题
    什么是“个人商业模式”?就是一个人出售自己时间的方式
    phpstudy如何安装ssl证书
    心不动——王阳明最可怕之处
    人间立命王阳明
    计算机视觉数据集
    ECG心电图数据2
    ECG心电图数据1
    梯度下降VS随机梯度下降
    SGD
  • 原文地址:https://www.cnblogs.com/lyd447113735/p/15348527.html
Copyright © 2011-2022 走看看