没有合适的资源?快使用搜索试试~ 我知道了~
spring-mvc/springboot使用MockMvc对controller进行测试
9 下载量 88 浏览量
2020-08-26
18:51:10
上传
评论
收藏 40KB PDF 举报
温馨提示
试读
1页
主要介绍了spring-mvc/springboot使用MockMvc对controller进行测试,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
资源推荐
资源详情
资源评论
spring-mvc/springboot使用使用MockMvc对对controller进行测试进行测试
主要介绍了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 {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setUp() throws Exception {
// mvc = MockMvcBuilders.standaloneSetup(new TestController()).build();
mvc = MockMvcBuilders.webAppContextSetup(context).build();//建议使用这种
}
@Test
public 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。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
资源评论
weixin_38677044
- 粉丝: 15
- 资源: 920
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功