我是靠谱客的博主 活泼老师,最近开发中收集的这篇文章主要介绍使用Mockito mock静态方法,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

在单测的时候,很多场景需要对静态方法进行mock打桩

之前在mockito2.x的时代需要借助powmock的功能

mockito在3.4.0版本也开始支持了静态方法的mock,使用方法如下

引入依赖包 mockito-inline


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

注意 mockito的版本必须在3.4.0及以上

 使用方式:

Mockito.mockStatic(Class<T> classToMock )

Example

@Test
void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() {
    assertThat(StaticUtils.name()).isEqualTo("Baeldung");

    try (MockedStatic<StaticUtils> utilities = Mockito.mockStatic(StaticUtils.class)) {
        utilities.when(StaticUtils::name).thenReturn("Eugen");
        assertThat(StaticUtils.name()).isEqualTo("Eugen");
    }

    assertThat(StaticUtils.name()).isEqualTo("Baeldung");
}

Mockito.mockStatic 的返回类型是一个MockedStatic对象,它是一个作用域模拟对象

这个类的注释如下:

Represents an active mock of a type's static methods. The mocking only affects the thread on which this static mock was created and it is not safe to use this object from another thread. The static mock is released when this object's close() method is invoked. If this object is never closed, the static mock will remain active on the initiating thread. It is therefore recommended to create this object within a try-with-resources statement unless when managed explicitly, for example by using a JUnit rule or extension.

大致意思就是mock的静态方法仅影响创建此静态模拟的线程,并且从另一个线程使用此对象是不安全的。当调用close() 方法时,静态模拟将会释放。如果此对象从未关闭,则静态模拟将在启动线程上保持活动状态。因此,建议在try-with-resources的语句中创建此对象,或者使用JUnit规则或者extension扩展去管理。

在close()之后再调用静态方法,会直接走真实的逻辑,也就是mock失效。

所以具体怎么做按照自己的场景来。

参考:

How to mock static methods with Mockito | FrontBackend

最后

以上就是活泼老师为你收集整理的使用Mockito mock静态方法的全部内容,希望文章能够帮你解决使用Mockito mock静态方法所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部