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

SpringBoot+Kotlin环境JUnit Mockito模拟Java方法类型转换错误

问题解决:Kotlin中Mock Java方法出现Unit转Boolean类型错误

环境配置

  • SpringBoot + Kotlin

问题场景

在Kotlin编写的JUnit测试中Mock Java方法时触发类型转换错误,错误代码及信息如下:

错误代码:

Mockito.`when`(workflowService.sendEvent(ArgumentMatchers.anyString(), ArgumentMatchers.anyString())).thenReturn(true)

错误信息:

class kotlin.Unit cannot be cast to class java.lang.Boolean 

class kotlin.Unit cannot be cast to class java.lang.Boolean (kotlin.Unit is in unnamed module of loader 'app'; java.lang.Boolean is in module java.base of loader 'bootstrap')

问题原因

你要Mock的Java方法sendEvent实际是void返回类型,但你使用了Mockito.when(...)的写法——这种写法仅适用于有返回值的方法。在Kotlin中调用Java的void方法会返回Unit类型,而后续的.thenReturn(true)尝试将Unit强制转换为Boolean,直接触发类型转换异常。

解决方法

方法1:使用Mockito的doReturn语法处理void方法

这是Mockito处理无返回值方法Mock的标准写法,调整代码顺序即可:

Mockito.doReturn(true).`when`(workflowService).sendEvent(ArgumentMatchers.anyString(), ArgumentMatchers.anyString())

注意:这里是先指定返回值(doReturn(true)),再绑定Mock对象(when(workflowService)),最后调用目标方法,和原写法顺序相反。

方法2:确认Java方法的返回类型

如果你的预期是sendEvent方法返回Boolean,检查是否引用了错误的方法重载——可能存在同名但返回类型为void的方法,通过IDE跳转至方法定义确认签名是否正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 03:52:05