如何使用SpringMockMvc测试http请求

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApplication.class)
@WebAppConfiguration
public class BaseTest {

    @Autowired
    protected WebApplicationContext webApplicationContext;

    protected MockMvc mockMvc;

    @Before
    public void setMockMvc() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void contextLoads() {
        System.out.println("=================================== Env start success! ===================================");
    }

    protected String perform(String url, Object request) throws Exception {
        return mockMvc.perform(
                // 请求的url,请求的方法
                post(url, request)
                        // 数据的格式
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(GsonUtil.getInstance().toJson(request)))
                // 打印出请求和相应的内容
                .andDo(print())
                // 返回的状态是200
                .andExpect(status().isOk())
                // 校验调用是否成功
                .andExpect(mvcResult -> {
                    BaseResponse br = GsonUtil.getInstance().fromJson(mvcResult.getResponse().getContentAsString(), BaseResponse.class);
                    if (!Constant.SUCCESS_CODE.equals(br.getCode())) {
                        throw new RuntimeException(br.getMessage());
                    }
                })
                // 将相应的数据转换为字符串
                .andReturn().getResponse().getContentAsString();
    }
}

BaseResponse 是我司自定义的基础返回报文,里面有统一的状态码,这里可以校验请求是否成功。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容