温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

spring-mvc/springboot使用MockMvc对controller进行测试

发布时间:2020-10-19 06:00:07 来源:脚本之家 阅读:172 作者:火光闪耀 栏目:编程语言

网上基本都是参考官方的使用方式,使用了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。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI