Springboot项目:使用MockMvc测试get和post接口(含单个和多个请求参数场景)
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@SpringBootTest
@AutoConfigureMockMvc
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testGetRequest() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/api/getData")
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
void testPostRequest() throws Exception {
String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
mockMvc.perform(MockMvcRequestBuilders.post("/api/postData")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
void testGetRequestWithQueryParam() throws Exception {
String queryParam = "paramValue";
mockMvc.perform(MockMvcRequestBuilders.get("/api/getDataWithQueryParam?queryParam=" + queryParam)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
void testPostRequestWithFormData() throws Exception {
String formData = "key1=value1&key2=value2";
mockMvc.perform(MockMvcRequestBuilders.post("/api/postDataWithForm")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.content(formData))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
}
评论已关闭