浅谈spring-boot的单元测试中,@Before不被执行的原因
我们先来看下笔者的单元测试的依赖版本:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
我用的是2.x的spring-boot,查阅的网上的资料,发现在新版本中,spring-boot用的是junit 5.x,这就发现问题了,在junit4.x版本之前,生效的是@Before主键,这没错。
然而在junit 5.x中,@Before主键被@BeforeEach所替代,因此就不生效了。
补充知识:springboot 2.0 单元测试配置踩的坑
1,错误配置1

会抛出
java.lang.Exception: No tests found matching [{ExactMatcher:fDisplayName=testSms], {ExactMatcher:fDisplayName=testSms(com.hm.system.manager.service.TestService)], {LeadingIdentifierMatcher:fClassName=com.hm.system.manager.service.TestService,fLeadingIdentifier=testSms]] from org.junit.internal.requests.ClassRequest@7ac7a4e4
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:37)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createFilteredTest(JUnit4TestLoader.java:77)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:68)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192
正确配置:

错误配置二

springboot 2.0版本只配置了 这个jar
会抛出 如下异常

正确配置

junit对springboot的版本有很强的依赖关系 ,别搞错了 ,2.0的请用 4.12 切记,踩过的坑!!!!
springboot 2.0后的版本,请添加 net.minidev.asm 的jar包
以上这篇浅谈spring-boot的单元测试中,@Before不被执行的原因就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
springBoot+webMagic实现网站爬虫的实例代码
这篇文章主要介绍了springBoot+webMagic实现网站爬虫的实例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-05-05
Java inputstream和outputstream使用详解
这篇文章主要介绍了Java inputstream和outputstream使用详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下2021-08-08


最新评论