SpringBootTest 學習筆記
前言
版本說明
platform-bom=Cairo-SR7
相關連結
- jsonPath github 連結: https://github.com/json-path/JsonPath
- spring io 官網: https://spring.io/projects/platform
實戰演練
package top.simba1949.web.controller;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* @RunWith(SpringRunner.class) 告訴JUnit使用Spring的測試支援
* @SpringBootTest 使用Spring Boot支援的引導,需要加載springboot的配置檔案
*
* @Author Theodore
* @Date 2019/12/2 15:15
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
/**
* 僞造 MVC 環境
*/
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void init(){
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
/**
* MockMvcRequestBuilders 建立請求方式
* @throws Exception
*/
@Test
public void whenQuerySuccess() throws Exception {
ResultActions resultActions = mockMvc.perform(
// 建立一個請求
MockMvcRequestBuilders.get("/user")
// 添加 contentType 資訊
.contentType(MediaType.APPLICATION_JSON_UTF8)
// 添加請求參數
.param("username", "test")
);
resultActions
// 執行結果期望
.andExpect(MockMvcResultMatchers.status().isOk())
// jsonPath 參考 https://github.com/json-path/JsonPath
.andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3));
}
}