You need to enable JavaScript to run this app. Mockito静态Mock在Spring WebFlux flatMap操作后失效问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

Mockito静态Mock在Spring WebFlux flatMap操作后失效问题咨询

WebFlux下Mockito静态Mock失效问题原因及解决方案

问题产生原因

  • Mockito的MockedStatic静态mock是线程绑定的,仅在创建该mock实例的线程中生效,一旦执行线程切换,mock规则就会失效。
  • WebFlux的flatMap操作符默认会根据运行场景自动切换调度线程,而第一个测试用例中的then操作没有显式指定调度器时,会沿用上游的执行线程,所以mock规则可正常生效;第二个用例进入flatMap后线程切换,mock规则失效,调用SecurityUtils.getCurrentUserId()会走真实的底层实现逻辑,最终抛出异常。

解决方案

方案1(推荐,符合WebFlux设计规范):放弃Mock静态方法,直接写入安全上下文

WebFlux的安全上下文本身存储在响应式流的Context中,直接往流内写入测试用的安全上下文即可,不需要mock静态方法,从根源避免线程绑定问题:

@Test
public void test2() {
    // 构造测试用的身份信息和安全上下文
    Authentication testAuth = new UsernamePasswordAuthenticationToken("test", null, Collections.emptyList());
    SecurityContext testSecurityContext = new SecurityContextImpl(testAuth);

    Mono<ResponseEntity<MappingJacksonValue>> testSource = Mono.just("something...")
        // 把安全上下文写入响应式流的Context
        .contextWrite(Context.of(SecurityContext.class, testSecurityContext))
        .then(reactionResource.create(getRandomRecord()))
        .flatMap(a -> reactionResource.create(getRandomRecord()))
        .then(reactionResource.create(getRandomRecord()));

    StepVerifier.create(testSource)
        .assertNext(next -> {
            String createdRecordId = extractId(next);
            Assertions.assertThat(createdRecordId).isNotBlank();
        })
        .verifyComplete();
}

方案2:强制指定响应式流全程在创建mock的线程执行

如果一定要使用静态mock,可显式指定整个流的调度器为当前测试线程,避免flatMap切换线程:

@Test
public void test2() {
    // 用try-with-resources包裹mock实例,测试结束自动关闭,避免线程污染
    try(MockedStatic<SecurityUtils> securityUtilsMockedStatic = Mockito.mockStatic(SecurityUtils.class)) {
        securityUtilsMockedStatic.when(SecurityUtils::getCurrentUserId).thenReturn(Mono.just("test"));

        Mono<ResponseEntity<MappingJacksonValue>> testSource = Mono.just("something...")
            // 强制指定流的所有操作都在当前线程执行
            .subscribeOn(Schedulers.immediate())
            .then(reactionResource.create(getRandomRecord()))
            .flatMap(a -> reactionResource.create(getRandomRecord()))
            .then(reactionResource.create(getRandomRecord()));

        StepVerifier.create(testSource)
            .assertNext(next -> {
                String createdRecordId = extractId(next);
                Assertions.assertThat(createdRecordId).isNotBlank();
            })
            .verifyComplete();
    }
}

内容的提问来源于stack exchange,提问作者Ravi Soni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 07:24:03