Spring Web API 测试

Spring Web API 测试,第1张

Spring Web API 测试

针对spring web API 做接口测试

依赖组件
        
            org.springframework.boot
            spring-boot-starter-test
            test
        

内部包含 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);
	}
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5685422.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存