Springboot微服务框架是目前越来越流行的框架,省去了很多繁琐的xml配置。最近新启了个项目,采用SpringBoot框架从头搭建,中间也遇到过各种坑,现在先描述一下 Junit4单元测试之坑吧。

结论:
@SpringBootTest注解,只会加载test路径下的资源文件(即xml配置),并不会加载main路径下的资源文件,这点很坑。。。

环境及问题描述:

  • 1.SpringBoot版本:2.0.0.RELEASE
  • 2.通过项目入口类启动Application.main() OK,能正常处理web请求
  • 3.启动单元测试,执行测试类,提示Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xx.xxx.service.SsoService' available,如下:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-02-02 16:26:10.537 ERROR 7812 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : ***************************
APPLICATION FAILED TO START
***************************Description:A component required a bean of type 'com.xx.xxx.service.SsoService' that could not be found.Action:Consider defining a bean of type 'com.xx.xxx.service.SsoService' in your configuration.2019-02-02 16:26:10.541 ERROR 7812 --- [           main] o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@93b025] to prepare test instance [com.jd.id.activity.ControllerTest@b9178]java.lang.IllegalStateException: Failed to load ApplicationContextat org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125) ~[spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:107) ~[spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190) ~[spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132) ~[spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:242) ~[spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) [spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) [spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) [spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) [spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) [spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) [spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na]at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51) [junit-rt.jar:na]at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) [junit-rt.jar:na]at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na]…………Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xx.xxx.service.SsoService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1509)at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:506)at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:484)at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:618)at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:177)at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:318)... 41 moreProcess finished with exit code -1

问题分析:

  • 1.首先com.xx.xxx.service.SsoService该类存在,并且项目正常启动时,并没有这个错误提示,那肯定是单元测试配置的有问题了,首先检查下相关的配置,@RunWith(SpringRunner.class)使用SpringRunner以便在测试开始的时候自动创建spring的应用上下文,没毛病。@SpringBootTest(classes = 启动类.class)配置也没问题,网上有讨论说springboot 1.4以下版本,要使用@SpringApplicationConfiguration(classes = 启动类.class),而我的项目版本是2.0,显然这个配置也没毛病。
    代码如下:
package com.xx.xxx.activity;import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;/*** 单元测试基类*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
//由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
@WebAppConfiguration
public class BaseTest
{@Beforepublic void init() {System.out.println("开始测试----------------");}@Afterpublic void destory() {System.out.println("结束测试----------------");}
}
  • 2.再看下pom文件的配置,引用了对应的test包,也没毛病
        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><version>${springboot.version}</version><scope>test</scope></dependency>
  • 3.对了,这个类是在src/main/resources目录下的资源文件里配置的,即xml中配置的bean,而src/test下并没有resources目录,莫非是这个原因?于是乎在test目录下创建resources路径,并把xml文件拷贝至test对应的路径下,结果能够正常进行单元测试了,数据也写入到数据库中,终于松了口气 -

准备就此作罢,不想在这个问题上浪费时间了,但是再做考虑,这样做欠妥,毕竟我每次改完xml文件的配置,必须得拷贝到test目录对应的文件夹下,这拷来拷去,并不是最好的解决方案啊,能不能打包时,把src/main/resources的资源文件也拷贝到src/test/resources中?这样就不用手工拷贝了。答案是:当然有了,看pom.xml配置:

<build><finalName>id-web-activity-root</finalName><resources><resource><directory>src/main/resources</directory><filtering>true</filtering><includes><include>**/*.*</include></includes></resource></resources><!--单元测试时引用src/main/resources下的资源文件--><testResources><testResource><directory>src/test/resources</directory></testResource><testResource><directory>src/main/resources</directory></testResource></testResources></build>

这时再去执行单元测试,正常执行,同时test-classes路径下已经有了xml资源配置文件,如下图:

单元测试的坑算是填了,再接着填其他坑吧。。。

springboot Junit单元测试之坑--@SpringBootTest注解无法加载src/main/resources目录下资源文件相关推荐

  1. SpringBoot打开resources目录下的文件操作

    SpringBoot打开resources目录下的文件操作 背景 我想在SpringBoot项目中放入一个静态文件.json文件.然后在SpringBoot项目内可以打开并读取此json文件. [外链 ...

  2. chrome浏览器加载css、js等静态资源文件的坑

    2019独角兽企业重金招聘Python工程师标准>>> 注意一点:在开发过程发现chrome加载的静态资源文件不是最新,则手工清除缓存和cooike再次刷新就可以了.原因是chrom ...

  3. SpringBoot模块中,resources目录下各文件夹作用

    文章目录 前言 1.public目录: 2.resources目录: 3.static目录: 4.templates目录: 5.src/main/resources目录(根目录): 6.META/IN ...

  4. Unity3D的坑系列:动态加载dll

    Unity3D的坑系列:动态加载dll 我现在参与的项目是做MMO手游,目标平台是Android和iOS,iOS平台不能动态加载dll(什么原因找乔布斯去),可以直接忽略,而在Android平台是可以 ...

  5. SpringBoot单元测试的@RunWith与@SpringBootTest注解

    SpringBoot测试类注解示例: import org.junit.runner.RunWith; import org.springframework.boot.test.context.Spr ...

  6. 使用IDEA+maven配置SSM项目步骤,以及配置项目过程中遇到的各种坑(SSM配置文件加载问题,使用注解开发问题,maven开发SSM项目步骤)

    问题概览 1. 更改springmvc配置文件的默认位置,但是"classpath:文件路径",路径明明正确,但是就是识别不到,idea报找不到配置文件的错误. 2. 使用myba ...

  7. SpringBoot:使用 @Lazy 注解懒加载

    为什么需要懒加载? 我们知道,在 SpringBoot 应用程序启动的时候,会实例化一些对象加入到 IOC 容器里边,这个过程是非常耗时的,那我们想要减少这个耗时的过程就需要 @Lazy 注解 对象加 ...

  8. Springboot Web应用中服务器配置参数ServerProperties的加载

    #概述 Springboot配置文件中以server开头的项表示服务器的配置参数,这一点从字面意义即可直观理解,这些参数,包括端口,路径设置,SSL配置参数等等.具体有哪些参数,从源代码的角度上,可以 ...

  9. SpringBoot+gradle+idea实现热部署和热加载

    前言 因为之前使用myeclipes的同学就知道,在使用myeclipes的时候,java文件或者jsp文件写完之后会被直接热加载到部署的容器中,从而在开发的时候,不同经常去重启项目,从而达到了增加开 ...

  10. springboot启动错误: 找不到或无法加载主类

    当在eclipse启动spring boot项目时出现问题: springboot错误: 找不到或无法加载主类 解决办法: 1,通过cmd命令行,进入项目目录进行,mvn clean install ...

最新文章

  1. gstreamer开发日志
  2. LipNet与ICLR评委互怼始末:名气大又怎样,还不是被拒绝了
  3. mac 下启动Android Studio 时出现 Android Studio was unable to find a valid Jvm
  4. 老兵的十年职场之路(二)
  5. 《Android开发从零开始》——26.数据存储(5)
  6. Eclipse R语言插件 statET 安装
  7. 【报告分享】2022年私域电商平台趋势报告.pdf(附下载链接)
  8. 直接拿来用!超实用的Java数组技巧攻略
  9. ajax 将输入框内容清空_Robot Framework清空输入框文本内容
  10. SetNamedPipeHandleState
  11. 计算机网络实验报告实验台,计算机控制实验台
  12. SpringBoot之整合thymeleaf渲染Web页面
  13. Unbalanced calls to begin/end appearance transitions for
  14. wps文档怎样去除广告
  15. 打印1000~2000年之间的闰年
  16. Windows Update启动不了如何解决?教你快速修复
  17. 2022第二届中国新能源汽车功能安全创新国际峰会
  18. 单片机应用系统设计技术——数控云台master
  19. 植物大战僵尸经典android,植物大战僵尸经典版
  20. 忆联发布数据中心级NVMe SSD——UH711a以及UH711a E3.S形态

热门文章

  1. 0204UNIFORM SIZE=10M?index?insert分裂
  2. c语言股票最大收益_C语言买卖股票问题
  3. 股票python量化交易014-计算收益率
  4. 【已解决】Python将网页内容保存为PDF (url转pdf)
  5. 交互式应用安全测试(IAST)学习笔记
  6. [Android]SurfaceView绘制奔跑的小人
  7. 音频ncm格式文件转mp3,ncm转mp3
  8. 考研和找工作都可以用的简历模板百度网盘链接
  9. fences卸载_fences是什么?fences栅栏桌面怎样安装卸载?
  10. java缓存机制面试题,电子版已问世