系列文章目錄
這是學透Spring Boot的第11篇文章。更多系列文章請關注 CSDN postnull 用戶的專欄
文章目錄
- 系列文章目錄
- Spring Test的依賴
- Spring Test的核心功能
- `@SpringBootTest` 加載Spring上下文
- 依賴注入有問題時
- Spring配置有問題時
- `@WebMvcTest` 測試Web層(Controller)
- MockMvc
- 更多場景
- Mock 和 Spy
- @RestClientTest 測試 RestClient
- 簡單測試
- MockRestServiceServer 的工作原理
- @DataJpaTest 測試JPA
- 簡單使用
- 原理
前一篇文章,我們介紹了UT、TDD、Mock、Spring Test等概念,本文我們重點來學習一下Spring Test。
Spring Test的依賴
我們要使用Spring Test 第一步要做的事情就是在pom.xml中引入Spring Boot Test的依賴
然后會自動關聯相關的依賴
這些被關聯進來的包,也就是Spring Test框架使用到的組件(可能是直接使用,也可能是間接使用到的,比如jsonPath就是間接使用, MockMvc封裝了jsonPath)。
組件的具體使用方法,請點擊下面組件的鏈接。
-
JUnit 5: 底層真正使用到單元測試框架.
-
Spring Test & Spring Boot Test: Spring Test的核心,提供了各種測試工具(類和注解)
-
AssertJ: 流式斷言
-
Hamcrest: 用來匹配對象
-
Mockito: Java Mock框架
-
JSONassert: 可以比較json的內容,而不是字符串匹配
-
JsonPath: JSON內容檢測
Spring Test的核心功能
Spring Test 提供了以下核心功能:
- @SpringBootTest:用于加載整個 Spring Boot 應用上下文
- @ContextConfiguration:用于加載特定的 Spring 配置。
- @MockBean 和 @SpyBean:用于模擬 Spring Bean。
- TestRestTemplate:用于測試 REST API。
- WebTestClient:用于測試 WebFlux 應用。
- @DataJpaTest:用來測試JAP 數據庫持久層的代碼
- @WebMvcTest:用來測試MVC層
Spring Test 會自動配置各種組件,類似Spring Boot的自動配置,自動配置模塊是 spring-boot-test-autoconfigure
。
每一種測試場景都是分別使用自己的注解,注解格式都是 @…?Test
,他們的自動配置類都是 @AutoConfigure…?
格式
測試模塊 | 注解 | 自動配置類 |
---|---|---|
測試Controller層 | @WebMvcTest | MockMvcAutoConfiguration |
測試JPA | @DataJpaTest | AutoConfigureTestDatabase |
測試Spring容器 | @SpringBootTest | |
測試RestClient | @RestClientTest | MockRestServiceServerAutoConfiguration |
@SpringBootTest
加載Spring上下文
一個SpringBoot應用,就是一個Spring ApplicationContext
(以前我們學習Spring容器時了解過的BeanFactory等各種層級的Spring容器)。
因為是Spring應用,所以我們需要加載完整的Spring Boot應用上下文,用來集成測試,包括我們的依賴正不正確,配置有沒有問題。
當然你也可以直接啟動 Spring Boot應用,但是那樣太麻煩(因為可能你的微服務依賴了一大堆外部系統,比如數據庫、ES等等)。
這時候我們只需要用注解@SpringBootTest
來加載Spring的上下文,快速驗證。
比如,正常情況,我們的測試用例可以通過。
@SpringBootTest
public class JoeApplicationTest {@Autowiredprivate JoeLabApplication applicationContext;@Test@DisplayName("測試Spring應用是否能夠啟動成功")public void contextLoads() {assertNotNull(applicationContext);}
}
依賴注入有問題時
為了測試是不是真的這么強大,我們可以稍微改動一下代碼。把我們的Service層的注解去掉
//@Service
public class TnUserService {public TypiUser getUserById(Integer id){return TypiUser.builder().id(id).name("Joe").username("joe").email("joe@gmail.com").build();}
}
這樣Controller層自動注入會找不到我們的Service。
@RestController
@RequestMapping("/tn-users")
public class TnUserController {private TnUserService tnUserService;public TnUserController(TnUserService tnUserService) {this.tnUserService = tnUserService;}
以前,你需要把Spring應用啟動才能發現這個問題,但是現在只需要執行測試用例。可以看到,測試用例失敗了,因為依賴注入有問題。
Spring配置有問題時
我們再換一個case,我們在test/resources下加一個配置application.properties
我們先只配置端口
server.port=6666
運行測試用例,發現報錯了。看錯誤日志。原來是因為我們的classpath下有數據庫的依賴,但是我們的Spring配置文件中沒有任何數據庫的配置造成的。
- 引入了數據庫JPA等依賴,就要在application.properties中配置數據庫連接,否則Spring應用啟動報錯的。
test/resources下放置了application.properties,Spring Test就不會去加載src/resources下的application.properties了
。
我們把數據庫的配置加上
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=abc123123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=true
這下,測試用例通過了。
我們再測試一下,配置有問題的情況. 我們把服務器端口改成abcde
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=aaaaa
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=trueserver.port=abcde
看日志可以看到,Spring Test去實例化Tomcat的bean時報錯了,端口只能是數字
@WebMvcTest
測試Web層(Controller)
直接使用Junit + Mockito,我們是不好測試Controller的。所以Spring Test 為我們提供了一個注解 @WebMvcTest
@WebMvcTest(TnUserController.class)
public class TnUserControllerTest {
加了這個注解的case,會自動的配置Spring MVC,并掃描Web相關的配置。比如加了@Controller
, @ControllerAdvice
等注解的類
但是它不會掃描
@Component
和@ConfigurationProperties
的Bean。
要掃描配置類,需要加上@EnableConfigurationProperties
注解
比@SpringBootTest
更輕量級!只關注Web層的東西。
MockMvc
我們一般不會單獨使用這個注解,而是結合@MockBean
和 MockMvc
來測試Controller。
MockMvc
這個類可以幫助我們在不需要啟動完整的HTTP服務器的前提下,測試MVC的控制器。
所以,我們的controller的ut通常是這樣的
@WebMvcTest(TnUserController.class)
public class TnUserControllerTest {@Autowiredprivate MockMvc mockMvc;@MockitoBeanprivate TnUserService tnUserService;@Test@DisplayName("測試成功查詢用戶的情況")public void testGetUser() throws Exception {//givenTypiUser mockUser = TypiUser.builder().id(1234).name("Joe").build();//whenwhen(tnUserService.getUserById(eq(1234))).thenReturn(mockUser);//thenmockMvc.perform(get("/tn-users/{id}", 1234)).andExpect(status().isBadRequest()).andExpect(jsonPath("$.id").value(1234)).andExpect(jsonPath("$.name").value("Joe"));}
}
jsonPath 用來解析json響應
更多場景
- 發送Post請求
mockMvc.perform(post("/api/user").contentType(MediaType.APPLICATION_JSON).content("{\"name\": \"Alice\"}")).andExpect(status().isOk()).andExpect(jsonPath("$.message").value("User created"));
- 使用jsonPath解析json響應
mockMvc.perform(get("/api/user/1")).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(1)).andExpect(jsonPath("$.name").value("Alice"));
- 請求待header和cookie
mockMvc.perform(get("/tn-users/{id}", 1234).header("Authorization", "Bearer token123").cookie(new Cookie("token", "token123"))).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(1234)).andExpect(jsonPath("$.name").value("Joe"));
- 獲取響應,進一步處理
MvcResult result = mockMvc.perform(get("/tn-users/{id}", 1234)).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(1234)).andExpect(jsonPath("$.name").value("Joe")).andReturn();
String resp = result.getResponse().getContentAsString();
System.out.println(resp);
Mock 和 Spy
Mock 和 Spy都是用來模擬一個類的行為,他們有什么區別呢?
mock用來完全替換一個類
mock是完全模擬,這個類的方法全都會被模擬,如果是void方法,什么也不做。
如果有返回值,這個方法就返回默認值,比如Integer就返回0
如果我們手動配置要返回的值,它就返回我們配置的值。
@Service
public class TnUserService {public Integer getNumber(){return 1000;}
}
@MockBeanprivate TnUserService tnUserService;@Test@DisplayName("測試成功查詢用戶數量的情況")public void testGetNumber() throws Exception {Integer result = tnUserService.getNumber();assertEquals(result, 0);verify(tnUserService, times(1)).getNumber();}
其實還是調用了一次的!!!!
Spy則剛剛相反,如果我們不做任何配置,調用它的方法就直接執行原來的邏輯,除非我們明確要mock它的行為。
@SpyBeanprivate TnUserService tnUserService;@Test@DisplayName("測試成功查詢用戶數量的情況")public void testGetNumber() throws Exception {Integer result = tnUserService.getNumber();assertEquals(result, 0);}
稍微改一下,我們還可以驗證方法的調用次數。
@Test@DisplayName("測試成功查詢用戶數量的情況")public void testGetNumber() throws Exception {Integer result = tnUserService.getNumber(1);assertEquals(result, 1000);verify(tnUserService, times(1)).getNumber(eq(1));}
注意@MockBean和@SpyBean都廢棄了
@Deprecated(since = "3.4.0", forRemoval = true)
@Target({ ElementType.TYPE, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(MockBeans.class)
public @interface MockBean {
官方推薦
Deprecated
since 3.4.0 for removal in 3.6.0 in favor of org.springframework.test.context.bean.override.mockito.MockitoBean
可以直接替換
@MockitoBeanprivate TnUserService tnUserService;@Test@DisplayName("測試成功查詢用戶數量的情況")public void testGetNumber() throws Exception {Integer result = tnUserService.getNumber(1);assertEquals(result, 0);}
@SpyBean也一樣
Deprecated
since 3.4.0 for removal in 3.6.0 in favor of org.springframework.test.context.bean.override.mockito.MockitoSpyBean
換了后,不知道為什么報錯。
Unable to select a bean to wrap: there are no beans of type com.joe.joelab.service.TnUserService (as required by field
解決:
這是因為 @WebMvcTest 只會加載Controller 相關的 Bean,不會自動加載 @Service、@Repository 等其他組件。
顯示的引入Service類
@WebMvcTest(TnUserController.class)
@Import(TnUserService.class)
public class TnUserControllerTest {@Autowiredprivate MockMvc mockMvc;@MockitoSpyBeanprivate TnUserService tnUserService;@Test@DisplayName("測試成功查詢用戶數量的情況")public void testGetNumber() throws Exception {Integer result = tnUserService.getNumber(1);assertEquals(result, 1000);}
為什么@SpyBean又能注入呢?
原理:使用@SpyBean 標注一個對象,其實Spring會代理這個對象。
@RestClientTest 測試 RestClient
RestClient是Spring6引入的輕量級同步HTTP客戶端
前面章節已經介紹過如何使用了
@Service
public class TypiRestClientService {private final RestClient.Builder builder;private RestClient restClient;public TypiRestClientService(RestClient.Builder builder) {this.builder = builder;}// 使用 @PostConstruct 注解在 Spring 完成構造器注入后再進行初始化@PostConstructpublic void init() {// 使用 builder 創建 RestClient 實例,進行初始化this.restClient = this.builder.baseUrl("https://jsonplaceholder.typicode.com").build();}public TypiUser getUser(Integer id) {return restClient.get().uri("/users/" + id).retrieve().body(TypiUser.class);}
簡單測試
這里我們來測試一下它
@RestClientTest
@Import(TypiRestClientService.class)
public class TypiRestClientServiceTest {@Autowiredprivate TypiRestClientService typiRestClientService;@Autowiredprivate MockRestServiceServer mockServer;@Testpublic void test(){this.mockServer.expect(requestTo("https://jsonplaceholder.typicode.com/users/1")).andRespond(withSuccess("{\"id\":1, \"name\":\"joe\"}", MediaType.APPLICATION_JSON));TypiUser user = this.typiRestClientService.getUser(1);assertEquals(1, user.getId());assertEquals("joe", user.getName());}}
- 測試 WebClient 調用外部 REST API 的邏輯,而不會真正發出 HTTP 請求,而是通過 MockRestServiceServer 模擬服務器響應。
- mockServer會攔截請求并返回響應
- @RestClientTest 不會加載Service類,所以要Import
MockRestServiceServer 的工作原理
- Spring Boot 在 @RestClientTest 里會自動配置 RestTemplate 或 RestClient:
- RestTemplate 需要一個 ClientHttpRequestFactory 作為底層的 HTTP 客戶端。
- MockRestServiceServer 創建了一個假的 ClientHttpRequestFactory,替換掉默認的 HTTP 處理邏輯。
- 當 RestTemplate 發出 HTTP 請求時:
- 由于 RestTemplate 依賴 ClientHttpRequestFactory,而這個工廠已經被 MockRestServiceServer 替換,所有的 HTTP 請求都不會真的出去,而是被攔截。
- MockRestServiceServer 會檢查是否有匹配的 expect() 規則:
- 如果 expect(requestTo(…)) 里定義了匹配的 URL,它就會返回你預設的響應(如 withSuccess(…))。
- 如果沒有匹配的規則,測試會報錯,表示請求沒有預期中的行為。
我們打個斷點,可以看到RestClient的factory已經被替換成mockserver了
如果我們要看源碼
可以看自動配置類
@AutoConfiguration
@ConditionalOnProperty(prefix = "spring.test.webclient.mockrestserviceserver",name = {"enabled"}
)
public class MockRestServiceServerAutoConfiguration {public MockRestServiceServerAutoConfiguration() {}@Beanpublic MockServerRestTemplateCustomizer mockServerRestTemplateCustomizer() {return new MockServerRestTemplateCustomizer();}@Beanpublic MockServerRestClientCustomizer mockServerRestClientCustomizer() {return new MockServerRestClientCustomizer();}@Beanpublic MockRestServiceServer mockRestServiceServer(MockServerRestTemplateCustomizer restTemplateCustomizer, MockServerRestClientCustomizer restClientCustomizer) {try {return this.createDeferredMockRestServiceServer(restTemplateCustomizer, restClientCustomizer);} catch (Exception var4) {throw new IllegalStateException(var4);}}
我們加了這個注解
@RestClientTest
@Import(TypiRestClientService.class)
public class TypiRestClientServiceTest {
其實它是一個符合注解
@TypeExcludeFilters({RestClientTypeExcludeFilter.class})
@AutoConfigureCache
@AutoConfigureWebClient
@AutoConfigureMockRestServiceServer
@ImportAutoConfiguration
public @interface RestClientTest {
它會自動打開自動配置的開關
@PropertyMapping("spring.test.webclient.mockrestserviceserver")
public @interface AutoConfigureMockRestServiceServer {boolean enabled() default true;
}
相當于配置了這個屬性:
spring.test.webclient.mockrestserviceserver = true
自動配置類看到這個是true,就開始配置mockFactory了
@ConditionalOnProperty(prefix = "spring.test.webclient.mockrestserviceserver",name = {"enabled"}
)
public class MockRestServiceServerAutoConfiguration {
@DataJpaTest 測試JPA
我們可以通過加@RestClientTest注解來測試JPA應用。
默認的,它會掃描@Entity類,并配置JPA Repository.
其它@Component的不會被掃描到。
如果內置的數據庫在classpath,比如h2,它也是會默認配置的。
Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one on the classpath or tune the replace attribute of @AutoConfigureTestDatabase.
我們一般要用h2來測試數據庫。
簡單使用
引入依賴
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.1.210</version><scope>test</scope></dependency>
然后test/resources下配置application.properties 配置數據庫
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
寫測試類
@DataJpaTest
public class BookJpaRepositoryTest {@Autowiredprivate TestEntityManager entityManager;@Autowiredprivate BookJpaRepository bookJpaRepository;@Testpublic void test(){Book book = new Book();book.setName("Hello Java");entityManager.persist(book);Book res = bookJpaRepository.findById(1L).get();assertEquals("Hello Java", res.getName());}
}
Spring Data JPA 測試會自動注入一個TestEntityManager 的bean到測試上下文,我們可以直接注入使用,用來操作數據庫,比如初始化一些測試數據。
原理
毫無疑問,還是自動配置做的好事。
起點還是測試類注解
@DataJpaTest
public class BookJpaRepositoryTest {
它是一個復合注解
@TypeExcludeFilters({DataJpaTypeExcludeFilter.class})
@Transactional
@AutoConfigureCache
@AutoConfigureDataJpa
@AutoConfigureTestDatabase
@AutoConfigureTestEntityManager
@ImportAutoConfiguration
public @interface DataJpaTest {String[] properties() default {};
配置默認內置的數據庫