当前位置:
首页 >
spring-mvc springboot 使用MockMvc对controller进行测试
发布时间:2025/7/14
55
豆豆
生活随笔
收集整理的这篇文章主要介绍了
spring-mvc springboot 使用MockMvc对controller进行测试
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
网上基本都是参考官方的使用方式,使用了import static,个人感觉这种方式特别不好,代码提示性不友好。所以在此进行说明,也方便自己以后使用。
1. 引入spring-test相关jar包,springboot只需引入spring-boot-starter-test即可
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>2. 写好controller,开始写test类
import org.front.server.Application; import org.front.server.web.control.TestController; import org.hamcrest.Matchers; 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.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; 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; //网上很多会在这里使用import static,主要导入的是MockMvcRequestBuilders,MockMvcResultMatchers,Matchers这三个类中的方法。/*** @author zz* @date 2017年7月4日* */ @RunWith(SpringJUnit4ClassRunner.class) //@SpringApplicationConfiguration(classes = MockServletContext.class)//这个测试单个controller,不建议使用 @SpringApplicationConfiguration(classes = Application.class)//这里的Application是springboot的启动类名。 @WebAppConfiguration public class ApplicationTests {@Autowiredprivate WebApplicationContext context;private MockMvc mvc;@Beforepublic void setUp() throws Exception {// mvc = MockMvcBuilders.standaloneSetup(new TestController()).build();mvc = MockMvcBuilders.webAppContextSetup(context).build();//建议使用这种}@Testpublic void test1() throws Exception {mvc.perform(MockMvcRequestBuilders.get("/data/getMarkers").contentType(MediaType.APPLICATION_JSON_UTF8).param("lat", "123.123").param("lon", "456.456").accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("SUCCESS")));} }
相信这样,基本开发过javaweb的就都能看懂了。通过方法的字面意思应该都能看懂方法含义,如果实在不懂请看源码或者官方API。
转载于:https://www.cnblogs.com/qlong8807/p/7121522.html
总结
以上是生活随笔为你收集整理的spring-mvc springboot 使用MockMvc对controller进行测试的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: C#学习系列之泛型类
- 下一篇: Apache OFBIZ高速上手(二)-