
针对spring web API 做接口测试
依赖组件org.springframework.boot spring-boot-starter-testtest
内部包含 Junit 4
- 针对 get、post 请求提供如下示例供参考
import lombok.extern.slf4j.Slf4j;
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.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
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.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@Slf4j
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ToolControllerTest {
private static final String postApiUrl = "/tool/postApiUrl";
private static final String getBizInfo = "/tool/getBizInfo";
@Autowired
WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void postApi() throws Exception {
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post(postApiUrl)
.contentType(MediaType.APPLICATION_JSON)
.param("resourceType", "XXX")
.param("bizType", "ABC")
.param("id", "7")
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value(1))
.andExpect(MockMvcResultMatchers.content().string("{"code":1,"msg":"OK","data":0,"success":true}"))
.andReturn();
String result = mvcResult.getResponse().getContentAsString();
LOGGER.info(result);
}
@Test
public void getBizInfo() throws Exception {
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.get(getBizInfo)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("resourceType", "XXX")
.param("bizCode", "234567890")
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value(1))
.andReturn();
String result = mvcResult.getResponse().getContentAsString();
LOGGER.info(result);
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)