场景
Java中进行单元测试junit.Assert断言、Mockito模拟对象、verify验证模拟结果、Java8中lambda的peek方法使用:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/127492361
上面讲了开发过程中一些测试方法。
如果需要在代码中直接测试某个Controller接口,除了每次启动项目后使用postman等测试工具测试外,
还可以使用MockMvc进行测试。
MockMvc
MockMvc 是 Spring 框架中的一个测试框架,用于模拟 HTTP 请求和响应。
MockMvc 可以模拟 Web 应用程序的环境,并且可以测试 Spring MVC 的控制器。
MockMvc 可以让我们测试 Spring MVC 控制器的行为和输出,而无需实际发送 HTTP 请求和接收响应。
MockMvc 提供了一种方式,用于模拟 Spring MVC 的请求和响应,并且可以使用 Spring MVC 的控制器进行测试。
MockMvc 可以模拟 HTTP 请求和响应,包括请求方法、请求头、请求参数、请求体、响应状态、响应头和响应体。
在 SpringBoot 中,我们可以使用 MockMvc 进行 Web 集成测试
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
实现
1、SpringBoot项目中添加如下依赖即可
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
当然SpringBoot所需的其它依赖也需要添加
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
其他业务依赖根据自己需求决定。
2、新建一个测试Controller
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @GetMapping("/test") public String test(@RequestParam("orderId") String orderId, String remark){ return "success"; } }
3、新建单元测试方法
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; 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.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @SpringBootTest class IdempotenceTest { @Autowired private WebApplicationContext webApplicationContext; @Test void test1() throws Exception { //初始化MockMvc MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); //循环调用5次进行测试 for (int i = 1; i <= 5; i++) { System.out.println("第"+i+"次调用接口"); //调用接口 String result = mockMvc.perform(MockMvcRequestBuilders.get("/test") .accept(MediaType.TEXT_HTML) .param("orderId","001") .param("remark","badao")) .andReturn() .getResponse() .getContentAsString(); System.out.println(result); } } }
这里模拟对以上controller进行5次请求。
4、MockMvc还提供了许多其他的方法,用于模拟HTTP请求和响应,具体可自行查阅其API。
一个具体的使用示例可参考
SpringBoot中接口幂等性实现方案-自定义注解+Redis+拦截器实现防止订单重复提交:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/131910440
- SpringBoot Controller 框架 接口 MockMvcspringboot controller框架 接口 controller mockmvc springboot controller框架service springboot controller接口 参数 resttemplate springmvc接口mockmvc springboot controller单元 接口 springboot controller repository service springboot controller service entity constructor springboot controller parameter springboot controller注意事项 事项