SpringBoot測試類注入Bean失敗的原因及分析
針對SpringBoot的測試類,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;
測試
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;
測試
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("-----");
}
}
注意包路徑需要一致
注意測試類的包名和啟動(dòng)類的包名一定要一致,否則掃描不到bean對象會(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-04
Java使用泛型實(shí)現(xiàn)棧結(jié)構(gòu)的示例代碼
泛型是JAVA重要的特性,使用泛型編程,可以使代碼復(fù)用率提高。本文將利用泛型實(shí)現(xiàn)簡單的棧結(jié)構(gòu),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-08-08
Java連接MySQL8.0 JDBC的詳細(xì)步驟(IDEA版本)
這篇文章主要介紹了Java連接MySQL8.0 JDBC的詳細(xì)步驟(IDEA版本),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
idea指定maven的settings文件不生效的問題解決
本文主要介紹了idea指定maven的settings文件不生效的問題解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
解讀CommandLineRunner和@PostConstruct區(qū)別與應(yīng)用場景
這篇文章主要介紹了解讀CommandLineRunner和@PostConstruct區(qū)別與應(yīng)用場景,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12

