使用Mockito 4.11.0测试Jasper报表Scala用例时遇类型不匹配错误
Mockito静态方法Mock类型不匹配问题原因分析
问题场景
使用Mockito-core 4.11.0版本在Scala单元测试中Mock Jasper报表的JasperFillManager静态方法时,执行代码出现类型不匹配错误:
测试代码
import org.mockito.Mockito._ import org.junit.Test @Test def testReportWithValidData() { // 其他Mock逻辑 val jasperFillManager: MockedStatic[JasperFillManager] = mockStatic(classOf[JasperFillManager]) jasperFillManager.when(JasperFillManager.fillReport(any(classOf[JasperReport]), any(classOf[java.util.Map[String,Object]]), any(classOf[JRDataSource]))) .thenReturn(mock(classOf[JasperPrint])) val result = ... assertNotNull(result) }
错误信息
type mismatch; found : net.sf.jasperreports.engine.JasperPrint required: org.mockito.MockedStatic.Verification
问题原因
Mockito 4.x版本对静态方法Mock的语法做了明确规范:MockedStatic.when()方法要求传入**MockedStatic.Verification类型的lambda表达式**,用来描述要Mock的静态方法调用行为。
你直接调用JasperFillManager.fillReport(...)会触发该静态方法的实际执行(或因未提前Mock导致异常),并返回JasperPrint类型对象,但when()方法需要的是Verification类型参数,两者类型完全不匹配,因此触发类型错误。
解决方法
将静态方法调用包裹在无参lambda表达式中,符合Mockito 4.x的语法要求:
jasperFillManager.when(() => JasperFillManager.fillReport(any(classOf[JasperReport]), any(classOf[java.util.Map[String,Object]]), any(classOf[JRDataSource]))) .thenReturn(mock(classOf[JasperPrint]))
这里的() => ...是Scala的无参lambda写法,会被Mockito识别为Verification类型参数,正确关联到要Mock的静态方法调用。
内容的提问来源于stack exchange,提问作者Adil
相关产品推荐
相关产品推荐

