目录
背景
进行单元测试编码时,使用了MybatisPlus,在对service层进行单元测试时,为保证数据与应用隔离,采用Mock的方式.
问题
Mockito对Mapper进行mock后,相关的TableInfo信息无法初始化,导致Wrapper组装条件时
报:com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: can not find lambda cache for this property [****] of entity [Entity]
我们在使用mybatisplus 时使用Lambda 表达式做查询条件会遇到mybatis拿不到缓存问题:
错误1:com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: can not find lambda cache for this entity
错误2:can not find lambda cache for this property [XXX] of entity [com.XXX.XXX]
分析
排错时发现LambdaUtils.getColumnMap(aClass)中无数据;
原因
首先是MybatisPlus的bug,经过分析后排除,再次考虑TableInfo的初始化过程被中止,或者被Mock替换了,更有可能是压根就没有触发。
项目中使用JUnit & Mocktio进行单元测试,如果代码中使用LambdaQueryWrapper进行条件构造,在DO类中有类似@TableId、@TableLogic等注解,在执行单元测试时会报错 MybatisPlusException: can not find lambda cache for this property [] of entity []
问题:Mockito对Mapper进行mock后,相关的TableInfo信息无法初始化,导致Wrapper组装条件时
报:com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: can not find lambda cache for this property [****] of entity [Entity]
解决方案
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), “”), TeamWorkerSearch.class) 这一行就行,其中TeamWorkerSearch 是你要做条件的entity 对象
解决的方案是手动触发相关缓存信息收集(或许还有更优雅的方案)
在执行目标方法之前添加如下内容:
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),Xxx.class);
假如一个test类里面使用到的方法多的话,可以使用before注解让这行代码在测试类中所有方法执行之前就添加。在junit 5.x中,@Before主键被@BeforeEach所替代。
@BeforeEach
public void initTable() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), Xxx.class);
}
或者
@Before
public void init() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), Xxx.class);
}
深层次原因
AbstractSqlInjector 会将所有 MapperBuilderAssistant 中的实体调用 initTableInfo
放到 TABLE_INFO_CACHE 这个map当中
然后在使用 LambdaQueryWrapper 做查询条件拼接的时候
它又会从 TABLE_INFO_CACHE 这个map中取出来