Spring Mockito语法错误:token 'boolean'后需指定维度问题排查
解决Mockito thenAnswer中返回boolean基本类型的错误问题
你遇到的问题核心是Java泛型不支持基本类型作为类型参数,而你在Answer的泛型声明里用了boolean(基本类型),这不符合语法要求。
错误原因分析
看你这段测试代码:
Mockito.when(avisDao.existsPortalContingut(AvisPortal.class.cast(Matchers.anyObject()))).thenAnswer(new Answer<boolean>(){ @Override public boolean answer(InvocationOnMock invocation) throws Throwable{ return true; } });
Mockito的Answer是泛型接口,它的类型参数必须是引用类型,而boolean是基本类型,不能直接用于泛型参数。Java里所有基本类型都有对应的包装类,这里应该用大写B的Boolean包装类。
修正后的代码
把泛型参数和返回类型都换成Boolean即可:
Mockito.when(avisDao.existsPortalContingut(AvisPortal.class.cast(Matchers.anyObject()))).thenAnswer(new Answer<Boolean>(){ @Override public Boolean answer(InvocationOnMock invocation) throws Throwable{ return true; // 这里true会自动装箱为Boolean类型 } });
额外优化建议
- 用Lambda简化代码:Java 8及以上可以用Lambda代替匿名内部类,代码更简洁:
Mockito.when(avisDao.existsPortalContingut(AvisPortal.class.cast(Matchers.anyObject()))) .thenAnswer(invocation -> true);
- 类型安全的匹配器:你现在用
Matchers.anyObject()加强制转换,可以直接用Matchers.any(AvisPortal.class)避免强制转换,更安全:
Mockito.when(avisDao.existsPortalContingut(Matchers.any(AvisPortal.class))) .thenAnswer(invocation -> true);
- 更简单的固定返回值写法:如果你只是要固定返回
true,其实不需要用thenAnswer,直接用thenReturn(true)更直观:
Mockito.when(avisDao.existsPortalContingut(Matchers.any(AvisPortal.class))) .thenReturn(true);
内容的提问来源于stack exchange,提问作者Kordh Rufan
相关产品推荐
相关产品推荐

