SpringBoot測(cè)試類注入Bean失敗的原因及分析
針對(duì)SpringBoot的測(cè)試類,2.2版本之前和之后是不一樣的。
2.2版本之后
導(dǎo)包pom.xml
添加test依賴
<!-- starter-test:junit + spring-test + mockito --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
注解
- @SpringBootTest—import org.springframework.boot.test.context.SpringBootTest;
- @Test—import org.junit.jupiter.api.Test;
測(cè)試
import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; /** * @author wangkanglu * @version 1.0 * @description * @date 2024-07-07 11:32 */ @SpringBootTest public class TestMain { @Test public void test1(){ System.out.println("-----"); } }
2.2版本之前
導(dǎo)包pom.xml
添加test依賴
<!-- starter-test:junit + spring-test + mockito --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
注解
- @SpringBootTest—import org.springframework.boot.test.context.SpringBootTest;
- @RunWith(SpringRunner.class)—import org.junit.runner.RunWith;
- @Test—import org.junit.Test;
測(cè)試
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; /** * @author wangkanglu * @version 1.0 * @description * @date 2024-07-07 11:32 */ @SpringBootTest @RunWith(SpringRunner.class) public class TestMain { @Test public void test1(){ System.out.println("-----"); } }
注意包路徑需要一致
注意測(cè)試類的包名和啟動(dòng)類的包名一定要一致,否則掃描不到bean對(duì)象會(huì)報(bào)空異常,如下圖:
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
struts2中實(shí)現(xiàn)多個(gè)文件同時(shí)上傳代碼
struts2中實(shí)現(xiàn)多個(gè)文件同時(shí)上傳代碼,需要的朋友可以參考一下2013-04-04Java使用泛型實(shí)現(xiàn)棧結(jié)構(gòu)的示例代碼
泛型是JAVA重要的特性,使用泛型編程,可以使代碼復(fù)用率提高。本文將利用泛型實(shí)現(xiàn)簡(jiǎn)單的棧結(jié)構(gòu),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-08-08Java連接MySQL8.0 JDBC的詳細(xì)步驟(IDEA版本)
這篇文章主要介紹了Java連接MySQL8.0 JDBC的詳細(xì)步驟(IDEA版本),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04idea指定maven的settings文件不生效的問(wèn)題解決
本文主要介紹了idea指定maven的settings文件不生效的問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06SpringMVC獲取請(qǐng)求參數(shù)的方法詳解
這篇文章主要為大家詳細(xì)介紹了SpringMVC中獲取請(qǐng)求參數(shù)的方法,例如通過(guò)ServletAPI獲取和通過(guò)控制器方法的形參獲取請(qǐng)求參數(shù)等,需要的可以參考下2023-07-07解讀CommandLineRunner和@PostConstruct區(qū)別與應(yīng)用場(chǎng)景
這篇文章主要介紹了解讀CommandLineRunner和@PostConstruct區(qū)別與應(yīng)用場(chǎng)景,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12