当前位置: 移动技术网 > IT编程>开发语言>Java > spring-mvc/springboot使用MockMvc对controller进行测试

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网