【Java】【SpringBoot】CP02:單元測試
This article is written by Xrilang(Chinese Name:萌狼藍天)
If you want find me ,You can contact me in BiliBili . My Bilibili name is 萌狼藍天
Of course, you can also add my QQ(My QQ number is: 3447902411)
(Please note that your sole purpose of adding me is limited to technical exchange. I won't help you with your homework!)
萌狼藍天 - 部落格園 | 萌狼工作室 - 萌狼藍天 (mllt.cc) | 萌狼藍天の技術棧 | Welcome !
在實際開發中,每當完成一個功能介面或業務方法的編寫後,通常都會藉助單元測試驗證該功能是否正確。
Spring Boot 對專案的單元測試提供了很好的支援,在使用時,需要提前在專案的pom.xml
檔案中新增spring-boot-starter-test
測試依賴啟動器,可以通過相關注解實現單元
測試。
新增測試依賴啟動器
注意:使用Spring Initiaizr方式搭建的Spring Boot專案會自動加入
spring-boot-starter-test
測試依賴啟動器,無需開發者手動新增
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
如果是自行新增,務必新增在
dependencies
範圍內<dependencies> <!--在此處新增--> </dependencies>
編寫單元測試類和測試方法
單元測試類
/**
* 使用Spring Initializr方式自動建立的主程式啟動類對應的單元測試類
*/
@RunWith(SpringRunner.class) //測試執行器,並載入Spring Boot測試註解
@SpringBootTest //標記單元測試類,並載入專案的上下文環境ApplicationContext
class Edu02CreateMySpringBootProjectApplicationTests {
//自動建立的單元測試方法示例
@Test
void contextLoads() {
}
}
單元測試方法
@Autowired //引入HelloController例項物件
private HelloController helloController;
@Test
public void helloControllerTest(){ //新增的單元測試方法
String hello = helloController.hello();//呼叫HelloController類中對應的請求控制方法hello()
System.out.println(hello);//列印輸出結果
}
/** * 使用Spring Initializr方式自動建立的主程式啟動類對應的單元測試類 */ @RunWith(SpringRunner.class) //測試執行器,並載入Spring Boot測試註解 @SpringBootTest //標記單元測試類,並載入專案的上下文環境ApplicationContext class Edu02CreateMySpringBootProjectApplicationTests { //自動建立的單元測試方法示例 @Test void contextLoads() { } @Autowired //引入HelloController例項物件 private HelloController helloController; @Test public void helloControllerTest(){ //新增的單元測試方法 String hello = helloController.hello();//呼叫HelloController類中對應的請求控制方法hello() System.out.println(hello);//列印輸出結果 } }
執行測試 滑鼠放在 helloControllerTest() 上右擊執行
作者:萌狼藍天,轉載請註明原文連結:https://www.cnblogs.com/mllt/p/springboot20220301cp2.html | 萌狼藍天@嗶哩嗶哩 | QQ:3447902411(僅限技術交流,新增請說明方向)| 歡迎關注我的嗶哩嗶哩