详解Spring MVC如何测试Controller(使用springmvc mock测试)

时间:2022-09-30 14:30:47

在springmvc中一般的测试用例都是测试service层,今天我来演示下如何使用springmvc mock直接测试controller层代码。

1.什么是mock测试?

mock测试就是在测试过程中,对于某些不容易构造或者不容易获取的对象,用一个虚拟的对象来创建以便测试的测试方法。

2.为什么要使用mock测试?

使用mock o bject进行测试,主要是用来模拟那些在应用中不容易构造(如httpservletrequest必须在servlet容器中才能构造出来)或者比较复杂的对象(如jdbc中的resultset对象)从而使测试顺利进行的工具。

3.常用注解

runwith(springjunit4classrunner.class): 表示使用spring test组件进行单元测试;

webappconfiguratio: 使用这个annotation会在跑单元测试的时候真实的启一个web服务,然后开始调用controller的rest api,待单元测试跑完之后再将web服务停掉;

contextconfiguration: 指定bean的配置文件信息,可以有多种方式,这个例子使用的是文件路径形式,如果有多个配置文件,可以将括号中的信息配置为一个字符串数组来表示;

4.安装测试环境

spring mvc测试框架提供了两种方式,独立安装和集成web环境测试(此种方式并不会集成真正的web环境,而是通过相应的mock api进行模拟测试,无须启动服务器)。

 独立安装测试方式

mockmvcbuilders.standalonesetup(object... controllers):通过参数指定一组控制器,这样就不需要从上下文获取了;

主要是两个步骤:

(1)首先自己创建相应的控制器,注入相应的依赖

(2)通过mockmvcbuilders.standalonesetup模拟一个mvc测试环境,通过build得到一个mockmvc

代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.xfs.test;
import org.junit.assert;
import org.junit.before;
import org.junit.test;
import org.springframework.test.web.servlet.mockmvc;
import org.springframework.test.web.servlet.mvcresult;
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 com.alibaba.fastjson.json;
import com.alibaba.fastjson.jsonobject;
import com.xfs.web.controller.apicontroller;
 
/**
 * 独立安装测试方式 springmvc mock测试
 *
 * @author admin
 *
 * 2017年11月23日 上午10:39:49
 */
public class testapione {
  private mockmvc mockmvc;
 
  @before
  public void setup() {
    apicontroller apicontroller = new apicontroller();
    mockmvc = mockmvcbuilders.standalonesetup(apicontroller).build();
  }
 
  @test
  public void testgetsequence() {
    try {
      mvcresult mvcresult = mockmvc.perform(mockmvcrequestbuilders.post("/api/getsequence"))
                .andexpect(mockmvcresultmatchers.status().is(200))
                .anddo(mockmvcresulthandlers.print())
                .andreturn();
      int status = mvcresult.getresponse().getstatus();
      system.out.println("请求状态码:" + status);
      string result = mvcresult.getresponse().getcontentasstring();
      system.out.println("接口返回结果:" + result);
      jsonobject resultobj = json.parseobject(result);
      // 判断接口返回json中success字段是否为true
      assert.asserttrue(resultobj.getbooleanvalue("success"));
    } catch (exception e) {
      e.printstacktrace();
    }
  }
 
}

请求结果如下:

详解Spring MVC如何测试Controller(使用springmvc mock测试)

详解Spring MVC如何测试Controller(使用springmvc mock测试)

详解Spring MVC如何测试Controller(使用springmvc mock测试)

集成web环境方式

mockmvcbuilders.webappcontextsetup(webapplicationcontext context):指定webapplicationcontext,将会从该上下文获取相应的控制器并得到相应的mockmvc;

主要是三个步骤:

(1)@webappconfiguration:测试环境使用,用来表示测试环境使用的applicationcontext将是webapplicationcontext类型的;value指定web应用的根

(2)通过@autowired webapplicationcontext wac:注入web环境的applicationcontext容器

(3)然后通过mockmvcbuilders.webappcontextsetup(wac).build()创建一个mockmvc进行测试

代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.xfs.test;
import org.junit.assert;
import org.junit.before;
import org.junit.test;
import org.junit.runner.runwith;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.mock.web.mockhttpsession;
import org.springframework.test.context.contextconfiguration;
import org.springframework.test.context.junit4.abstractjunit4springcontexttests;
import org.springframework.test.context.web.webappconfiguration;
import org.springframework.test.web.servlet.mockmvc;
import org.springframework.test.web.servlet.mvcresult;
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 com.alibaba.fastjson.json;
import com.alibaba.fastjson.jsonobject;
 
/**
 * 集成web环境方式 springmvc mock测试
 *
 * @author admin
 *
 * 2017年11月23日 上午11:12:43
 */
@runwith(junit4classrunner.class)
@webappconfiguration
@contextconfiguration(locations = { "classpath*:spring/*.xml" })
public class testapitwo extends abstractjunit4springcontexttests {
 
  @autowired
  public webapplicationcontext wac;
 
  public mockmvc mockmvc;
 
  public mockhttpsession session;
 
  @before
  public void before() throws exception {
    mockmvc = mockmvcbuilders.webappcontextsetup(wac).build();
  }
 
  @test
  public void testgetsequence() {
    try {
      mvcresult mvcresult = mockmvc.perform(mockmvcrequestbuilders.post("/api/getsequence"))
                .andexpect(mockmvcresultmatchers.status().is(200))
                .anddo(mockmvcresulthandlers.print())
                .andreturn();
      int status = mvcresult.getresponse().getstatus();
      system.out.println("请求状态码:" + status);
      string result = mvcresult.getresponse().getcontentasstring();
      system.out.println("接口返回结果:" + result);
      jsonobject resultobj = json.parseobject(result);
      // 判断接口返回json中success字段是否为true
      assert.asserttrue(resultobj.getbooleanvalue("success"));
    } catch (exception e) {
      e.printstacktrace();
    }
  }
 
}

运行结果和上面独立测试时候一样。

总结:

整个过程:

1、mockmvc.perform执行一个请求;

2、mockmvcrequestbuilders.get("/user/1")构造一个请求

3、resultactions.andexpect添加执行完成后的断言

4、resultactions.anddo添加一个结果处理器,表示要对结果做点什么事情,比如此处使用mockmvcresulthandlers.print()输出整个响应结果信息。

5、resultactions.andreturn表示执行完成后返回相应的结果。

整个测试过程非常有规律:

1、准备测试环境

2、通过mockmvc执行请求

3、添加验证断言

4、添加结果处理器

5、得到mvcresult进行自定义断言/进行下一步的异步请求

6、卸载测试环境

参考: spring-mvc-test-framework

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

原文链接:http://www.linuxidc.com/Linux/2017-12/149851.htm