編寫springboot測試類
依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
import org.junit.Assert;
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.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;
@Transactional //測試後數據h會回滾
@WebAppConfiguration
@SpringBootTest
@RunWith(SpringRunner.class)
public class RequestAPITest {
private MockMvc mvc;
@Autowired
WebApplicationContext webContext;
@org.junit.Before
public void before(){
mvc = MockMvcBuilders.webAppContextSetup(webContext).build();
}
@Test
public void test() throws Exception {
//請求頭
HttpHeaders headers = new HttpHeaders();
//請求參數
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
//請求URI
String uri = "/person/get";
headers.add("head", "");
params.add("age", "10");
MvcResult result = mvc.perform(
//MockMvcRequestBuilders.post(uri)
MockMvcRequestBuilders.get(uri)
.headers(headers)
.params(params)
.accept(MediaType.APPLICATION_JSON_UTF8)
).andReturn();
int status = result.getResponse().getStatus(); //獲取執行結果的狀態
String content= result.getResponse().getContentAsString(); //獲取響應內容
System.out.println("返回結果 "+ status + " "+ content);
Assert.assertEquals("錯誤", 200,status);
}
}
/*
mvc.perform(
MockMvcRequestBuilders.get(uri)
.headers(headers)
.params(params)
.accept(MediaType.APPLICATION_JSON_UTF8)
).andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string(equalTo("")));
*/