多线程环境中使用 Mockito 来 Mock 静态方法

回看三年前的一篇日志 Mockito 3.4.0 开始可 Mock  静态方法,最后对 Mockito 产生的缺憾是它无法用来 Mock 非测试线程(主线程)中的静态方法调用。其实这也是可以变通的,下面慢慢道来。

首先回顾一下 Mockito  的静态方法 Mock 的使用方法,随着 Mockito 版本的升级,引入依赖的方式也发生了些许的变化,以 Maven 项目为例,如果在 JUnit 5 下用 Mockito 的 pom.xml 依赖中为

1

2

3

4

5

6

<dependency>

    <groupId>org.mockito</groupId>

    <artifactId>mockito-junit-jupiter</artifactId>

    <version>5.14.1</version>

    <scope>test</scope>

</dependency>

由它引入的全部相关依赖

阅读全文 >>

The used MockMaker PowerMockMaker 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'. Note that Mockito's inline mock maker is not supported on Android. org.mockito.exceptions.base.MockitoException: The used MockMaker PowerMockMaker 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'. Note that Mockito's inline mock maker is not supported on Android. 下面的代码段未通过,出现了上述的错误,这应该怎么解决 @Test public void testSingleton_threadSafety() throws InterruptedException { // 使用 MockedStatic 模拟静态方法Mockito 3.4+ 特性) try (MockedStatic<PackageDataManager> mocked = Mockito.mockStatic(PackageDataManager.class)) { // 设置模拟行为 PackageDataManager mockInstance = mock(PackageDataManager.class); mocked.when(PackageDataManager::getInstance).thenReturn(mockInstance); // 创建测试线程 final PackageDataManager[] instances = new PackageDataManager[2]; Thread t1 = new Thread(() -> instances[0] = PackageDataManager.getInstance()); Thread t2 = new Thread(() -> instances[1] = PackageDataManager.getInstance()); t1.start(); t2.start(); t1.join(); t2.join(); // 验证结果 assertSame(instances[0], instances[1]); verify(mockInstance, times(2)).getInstance(); } }
最新发布
07-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值