You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mockito模拟Reactor Mono出现MonoJust/toString类型不匹配错误排查与解决

错误原因与解决方法

错误原因

  1. Mockito语法触发的方法调用问题
    使用given(mock.method(...)).willReturn(...)时,Mockito会先执行mock.method(...)调用。@MockBean生成的mock对象默认返回null,当返回类型是Reactor的Mono时,Mockito内部处理null的过程中触发了toString()调用,导致类型不匹配(MonoJust不是String类型),抛出错误。

  2. 接口参数定义错误
    你提供的MfaTokenService接口中,createNewToken方法存在两个同名参数sessionId(类型分别为String和UUID),这会导致编译错误,同时也可能干扰测试逻辑的正确性。

  3. Mock初始化时机潜在问题
    虽然@TestInstance(PER_CLASS)允许@BeforeAll方法使用成员变量,但在部分场景下,@MockBean的初始化可能滞后于@BeforeAll执行,导致mock对象未完全就绪,间接引发错误。

解决方法

1. 替换Mockito语法为doReturn...when

这是处理Reactor类型mock的标准方式,可避免触发实际方法调用:

@BeforeAll
protected void init() {
    Mono<Token> tokenExpected = Mono.just(new Token());

    // 替换given...willReturn为doReturn...when
    doReturn(tokenExpected)
        .when(this.tokenService)
        .createToken(
            any(Auth.class),
            any(String.class),
            any(UUID.class),
            any(String.class),
            any(Duration.class)
        );

    this.accessService = new AccessService(this.tokenService, this.userService);
}

2. 修正接口参数重名问题

修改MfaTokenService的参数名称,避免重复:

public interface MfaTokenService {
  Mono<MfaToken> createNewToken(Auth authentication,
                                 String clientSessionId, // 重命名第一个sessionId
                                 UUID serverSessionId,   // 重命名第二个sessionId
                                 String phone,
                                 Duration ttl);
}

3. 确认依赖完整性

确保测试依赖中包含Mockito对Reactor的支持(Spring Boot项目中spring-boot-starter-test已默认包含),普通项目需添加:

<!-- Maven依赖示例 -->
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-reactor</artifactId>
    <scope>test</scope>
</dependency>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:14:57