TestNG的静态方法mock的步骤

最近团队内部对程序中使用大量的静态方法,而公司要求要有sonar扫描覆盖率的,因为在大量使用静态方法的地方若不mock,则覆盖率达不到。于是网上很少的文章讲解对静态方法的mock,大多都是如何使用powermockJunit,一般对于privatepublic方法正常逻辑是有文章讲解,那么今天我就把静态方法覆盖的方式梳理了一下。避免每个人过来都来问口口相传,形成文档。

在Test方法中需要用到TimeUtil.java中的静态方法。示例Mock操作如下:

1.添加maven配置依赖

     <!-- 单元测试mock -->
     <dependency>
         <groupId>org.mockito</groupId>
         <artifactId>mockito-all</artifactId>
         <scope>test</scope>
     </dependency>
     <dependency>
         <groupId>org.powermock</groupId>
         <artifactId>powermock-core</artifactId>
         <scope>test</scope>
     </dependency>
     <dependency>
         <groupId>org.powermock</groupId>
         <artifactId>powermock-api-mockito</artifactId>
         <scope>test</scope>
     </dependency>
     <dependency>
         <groupId>org.powermock</groupId>
         <artifactId>powermock-module-testng</artifactId>
         <scope>test</scope>
     </dependency>
    
     <dependency>
         <groupId>org.testng</groupId>
         <artifactId>testng</artifactId>
         <scope>test</scope>
     </dependency>
     <!-- 单元测试 -->

2.在Test类添加以下注解

    @SuppressStaticInitializationFor("com.yuesf.utils.TimeUtil")
    @PowerMockIgnore("java.lang.*")
    @PrepareForTest(value = TimeUtil.class)
    public class SaleOrderBizImplTest {
    }   

3.Test类中添加以下方法

  @ObjectFactory
    public IObjectFactory getObjectFactory() {
        return new org.powermock.modules.testng.PowerMockObjectFactory();
    }
@BeforeClass(alwaysRun = true)
    public void setUp()  {
        MockitoAnnotations.initMocks(this);
}

4.在测试方法添加以下注解

    @PrepareForTest(TimeUtil.class)

示例

    @PrepareForTest(TimeUtil.class)
    @Test
    public void processOrderItemLabel() {
    }

验证结果:


eSHuPH.png

再次感谢您已看完全文,欢迎关注微信公众号猿码 ,您的关注我会持续更新文章!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容