淺談spring-boot的單元測試中,@Before不被執(zhí)行的原因
我們先來看下筆者的單元測試的依賴版本:
<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,查閱的網(wǎng)上的資料,發(fā)現(xiàn)在新版本中,spring-boot用的是junit 5.x,這就發(fā)現(xiàn)問題了,在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后的版本,請?zhí)砑?net.minidev.asm 的jar包
以上這篇淺談spring-boot的單元測試中,@Before不被執(zhí)行的原因就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
springBoot+webMagic實現(xiàn)網(wǎng)站爬蟲的實例代碼
這篇文章主要介紹了springBoot+webMagic實現(xiàn)網(wǎng)站爬蟲的實例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05
Java inputstream和outputstream使用詳解
這篇文章主要介紹了Java inputstream和outputstream使用詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08

