SpringBoot中Junit测试注入Bean失败的解决方法

在SpringBoot中使用Junit做测试的时候测试DAO层的接口,但是一直提示注入Bean失败,报以下错误:


org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'hellowood.TestFeedbackMapper': Unsatisfied dependency expressed through field 'feedbackDetailMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'hellowood.lntu.oe.wmp.dao.FeedbackDetailMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}


在查询了其他项目的Junit后发现Junit的注解是这样的


@RunWith(SpringJUnit4Cla***unner.class)

@SpringApplicationConfiguration(classes = Application.class)

@WebAppConfiguration


而新建的项目中是这样的


@RunWith(SpringRunner.class)

@SpringBootTest

@WebAppConfiguration


直接修改注解后发现不能引入SpringApplicationConfiguration,而所有的依赖只是版本不一样,查阅了Spring官方文档后发现新版中用SpringBootTest代替了SpringApplicationConfiguration,所以将注解改为以下形式就可以正常注入Bean了


@RunWith(SpringRunner.class)

@SpringBootTest(classes = Application.class)

@WebAppConfiguration

欢迎工作一到五年的Java工程师朋友们加入Java技术交流群:659270626
群内提供免费的Java架构学习资料(里面有高可用、高并发、高性能及分布式、Jvm性能调优、Spring源码,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多个知识点的架构资料)合理利用自己每一分每一秒的时间来学习提升自己,不要再用"没有时间“来掩饰自己思想上的懒惰!趁年轻,使劲拼,给未来的自己一个交代!


上一篇:spring boot 单元测试


下一篇:OCP 063中文考试题库(cuug内部资料)第25题