Spring Boot 測試詳解
1. 測試依賴引入
Spring Boot 默認通過以下 Maven 依賴引入測試工具:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>
該依賴包含 JUnit 5、Mockito、AssertJ 等核心測試庫,支持單元測試、集成測試和 Mock 測試。
2. IDE 自動創建測試類
IDE(如 IntelliJ/Eclipse)會自動生成測試類,示例如下:
@SpringBootTest
class Chapter15ApplicationTests {@Testvoid contextLoads() {// 驗證應用上下文是否加載成功}
}
@SpringBootTest
:加載完整的 Spring Boot 應用上下文。@Test
:JUnit 5 標注測試方法。
3. 測試注解詳解
注解 | 作用 |
---|---|
@SpringBootTest | 加載完整的 Spring Boot 應用上下文,支持配置 webEnvironment 等參數。 |
@Test | JUnit 5 標注測試方法。 |
@Autowired | 從 Spring 容器中注入 Bean。 |
@MockBean | 在測試上下文中模擬 Bean(Mockito)。 |
@WebMvcTest | 僅加載 Web 層(Controller),不啟動完整上下文。 |
@DataJpaTest | 僅加載 JPA 相關配置,用于數據庫測試。 |
4. 業務層測試
場景:測試 UserService
的 getUser()
方法。
@SpringBootTest
class UserServiceTests {@Autowiredprivate UserService userService;@Testvoid testGetUser() {User user = userService.getUser(1L);Assertions.assertNotNull(user, "用戶對象不能為空");}
}
- 關鍵點:
- 通過
@Autowired
注入業務層 Bean。 - 使用
Assertions
(JUnit 5)或Assert
(JUnit 4)進行斷言。
- 通過
5. REST 風格測試
場景:測試 REST 接口 /user/{id}
,使用隨機端口避免沖突。
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {@Autowiredprivate TestRestTemplate restTemplate;@Testvoid testGetUser() {User user = restTemplate.getForObject("/user/{id}", User.class, 1L);Assertions.assertNotNull(user, "用戶對象不能為空");}
}
- 關鍵點:
webEnvironment = RANDOM_PORT
:啟動隨機端口的嵌入式服務器。TestRestTemplate
:簡化 REST 接口調用。
6. Mock 測試(Mockito)
場景:模擬 ProductService
的 getProduct()
方法。
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ProductClientTest {@MockBeanprivate ProductService productService;@Testvoid testMockProduct() {Product mockProduct = new Product(1L, "產品名稱", "產品描述");BDDMockito.given(productService.getProduct(1L)).willReturn(mockProduct);Product result = productService.getProduct(1L);Assertions.assertNotNull(result, "產品對象不能為空");}
}
- 關鍵點:
@MockBean
:在 Spring 上下文中替換真實 Bean 為 Mock。given().willReturn()
:定義 Mock 方法的返回值。- Mockito 風格:BDD 風格(
given-when-then
)或經典風格(when-thenReturn
)。
7. 測試類型總結表
測試類型 | 適用場景 | 關鍵注解/工具 |
---|---|---|
業務層測試 | 業務邏輯驗證(Service 層) | @SpringBootTest , @Autowired |
REST 接口測試 | 控制器接口(Controller)測試 | TestRestTemplate , RANDOM_PORT |
Mock 測試 | 模擬外部依賴(如未實現的服務) | @MockBean , Mockito |
集成測試 | 跨層協作測試(如數據庫) | @DataJpaTest , @Transactional |
8. 注意事項
- Mockito 版本:Spring Boot 2.x 默認集成 Mockito 3.x,需注意語法差異。
- 測試隔離:Mock 測試需確保模擬行為僅作用于當前測試方法。
- 隨機端口:測試時需通過
LocalServerPort
注入實際端口(如需訪問外部 URL)。
通過以上配置和示例,可覆蓋 Spring Boot 應用的各類測試場景,提升代碼質量和開發效率。