admin管理员组

文章数量:1530085

项目场景:

在编写SpringBoot+Mybatis项目时,进行Service单元测试时的报错


问题描述

主要问题:Unsatisfied dependency expressed through field ‘XXXService’;

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.passwordtranslate.Service.ServiceImpl.UsersServiceImplTest': Unsatisfied dependency expressed through field 'usersService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.passwordtranslate.Service.UsersService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: 
.......

原因分析:

ServiceBean没有成功注入Spring容器中


当前的结构目录:


Service层与Mapper均添加注释:


单元测试显示找不到该bean:


测试结果:


解决方案:

springboot启动类的默认扫描路径是该类所在的包下面的所有java类。如:启动类在“com.passwordtranslate.testone”包下,那么只有com.passwordtranslate.testone包下的类会被扫描加载。


将启动类移动至com.passwordtranslate包下(往上抬一阶)


启动类
(如果本文中提到的方法不奏效,也注意一下启动类的@MapperScan有没有添加和添加对(路径要到Mapper层所在的包))


Mapper类和Service类中的小bean图标出现


测试类中的bean也显示注入成功
(自己写的测试类@SpringBootTest一定要写上classes属性)


最后运行结果:成功查询

本文标签: 时报单元测试MyBatisServiceSpringBoot