1,测试类示例:
package com.gwm.ma.sms.api.domain.test.controller; import cn.hutool.json.JSONUtil; import com.gwm.ma.sms.api.domain.sendTask.controller.form.SmsSendParamForm; import com.gwm.ma.sms.api.domain.signature.controller.form.*; import com.gwm.ma.sms.api.domain.template.controller.form.*; import com.gwm.ma.sms.api.domain.test.controller.form.TestForm; import lombok.extern.slf4j.Slf4j; 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.RequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @Slf4j @AutoConfigureMockMvc @SpringBootTest public class TestControllerTest { @Autowired TestController testController; @Autowired private MockMvc mockMvc; @Test public void test1() { } @Test public void testPost() throws Exception { // MockMvc mockMvc = new MockMvc(); TestForm testForm = new TestForm(); testForm.setName("zhangsan"); String content = JSONUtil.toJsonStr(testForm); //构造请求参数 RequestBuilder rb = MockMvcRequestBuilders.post("/test/post") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(content); //发送请求,验证返回结果 String result = mockMvc.perform(rb) .andExpect(status().isOk()) // .andExpect(MockMvcResultMatchers.jsonPath("$.data.name").value("zhangsan")) .andReturn().getResponse().getContentAsString(); log.info(result); }
2,所需要jar包
<!-- test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency>