springBoot Junit測試用例出現@Autowired不生效的解決
springBoot Junit測試用例出現@Autowired不生效
前提條件:
1,測試類上面添加支持的注解
就能取到spring中的容器的實例,如果配置了@Autowired那么就自動將對象注入。
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class)//這里Application是啟動類
pom文件添加:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-test</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.25.RELEASE</version> <scope>compile</scope> </dependency>
2,出現錯誤
java.lang.NoSuchMethodError: org.springframework.util.Assert.state(ZLjava/util/function/Supplier;)V
這種錯誤的出現一般都是jar包沖突,這里是將spring-test的版本號由5.1.11版本換成了4.3.25解決了(可參考比較spring-context的版本),當重復引用時也會提示錯誤,所以引入時需要注意!
3,注解解釋
@runWith注解作用:
- – @RunWith就是一個運行器
- – @RunWith(JUnit4.class)就是指用JUnit4來運行
- – @RunWith(SpringJUnit4ClassRunner.class),讓測試運行于Spring測試環(huán) 境,以便在測試開始的時候自動創(chuàng)建Spring的應用上下文
- – @RunWith(Suite.class)的話就是一套測試集合
SpringTest與JUnit等其他測試框架結合起來,提供了便捷高效的測試手段。而SpringBootTest 是在SpringTest之上的再次封裝,增加了切片測試,增強了mock能力。
4,junit測試如何在idea上通過類中方法直接生成測試用例
第一步
從插件資源庫中搜索JunitGenerator V2.0插件并安裝
第二步
配置測試用例的生成目錄
- 1.打開File->Settings
- 2.搜索junit,找到JUnit Generator
- 3.Properties選項卡里的Output Path為測試用例生成的目錄,修改為test目錄:${SOURCEPATH}/../../test/java/${PACKAGE}/${FILENAME}
- 4.切換到JUnit 4選項卡,可以修改生成測試用例的模板,比如類名、包名等
第三步
為指定的方法創(chuàng)建自動創(chuàng)建測試用例右鍵
Junit中@Autowired失效
今天學習spring注解的時候,用junit來測試
利用注解在容器中創(chuàng)建Student對象
然后用@Autowired注解進行自動裝配
出現了空指針異常
原因
在Test方法執(zhí)行的時候,并不會給你創(chuàng)建容器,junit也不知道你是否在使用spring,默認單例模式下沒有容器也就不會有@Autowired自動裝配有效
解決方案
1. 導入 Spring 整合 Junit 的 jar包
在pom.xml中加入依賴
... <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.2.RELEASE</version> </dependency> ...
注意在使用5.x的spring依賴時,junit版本需要在4.12及以上
2. 使用 Junit 提供的一個注解 –@Runwith把原有的 main 方法替換了,替換成 Spring 提供
3. 告知 Spring 的運行器, Spring 和 ioc 創(chuàng)建是基于 xml 還是注解的,并且說明位置,用到的注解如下
@ContextConfiguration
Locations : 指定 xml 文件的位置,加上 classpath 關鍵字,表示在類路徑下(適用于使用xml文件進行IOC)
classes : 指定注解類所在地位置(適用于你使用新創(chuàng)建的配置類取代xml文件進行IOC)
如下:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class test010 { @Autowired Student student; @Test public void test() { student.say(); } }
運行結果
hello,Student
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
springboot+mybatis-plus基于攔截器實現分表的示例代碼
本文主要介紹了springboot+mybatis-plus基于攔截器實現分表,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11