使用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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值