MockMvc 来自Spring Test,它允许您通过一组方便的builder类向 DispatcherServlet 发送HTTP请求,并对结果作出断言。请注意,@AutoConfigureMockMvc 与@SpringBootTest 需要一起注入一个MockMvc 实例。在使用@SpringBootTest 时候,我们需要创建整个应用程序上下文。
示例代码:
import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.annotation.Rollback; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.transaction.annotation.Transactional; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class)//表示使用Spring Test组件进行单元测试 @Transactional//回滚所有增删改 @SpringBootTest @AutoConfigureMockMvc//注入一个MockMvc实例 public class DingControllerTest { private final static Logger logger = LoggerFactory.getLogger(DingControllerTest.class); @Autowired private MockMvc mockMvc; @Test @Rollback(false)//取消回滚public void getSignature() throws Exception { String responseString = mockMvc.perform( post("/ding/getSignature")//请求的url,请求的方法是post .contentType(MediaType.APPLICATION_JSON)//数据的格式 .param("url", "https://www.baidu.com/")//添加参数 ).andExpect(status().isOk())//返回的状态是200 .andExpect(MockMvcResultMatchers.jsonPath("$.state").value(1)) //判断某返回值是否符合预期 .andDo(print())//打印出请求和相应的内容 .andReturn().getResponse().getContentAsString();//将相应的数据转换为字符串 logger.info("post方法/ding/getSignature,{}", responseString); } }
官方文档:
https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-with-mock-environment