https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html#spring-mvc-test-framework

1 创建MockMvc 对象

package com.wanghengzhi.dadada;

import com.fasterxml.jackson.databind.ObjectMapper;
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.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

/**
 * 测试启动类
 * @author wanghengzhi
 * @since 2020.9.2
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class ApplicationTest {

    protected MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;
    /**
     * jackson
     */
    @Autowired
    protected ObjectMapper jacksonMapper;

    /**
     * 构造MockMvc
     */
    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void empty() {
        System.out.println("Begin Testing With TDD !");
    }

}

2 发起请求

2.1 构建请求的工具类

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
  • MockMvcRequestBuilders 构造request.

  • MockMvcResultHandlers 构造结果处理类,怎样处理结果。例如打印response

  • MockMvcResultMatchers 构造结果预期类,相当于junit的断言。例如判断http状态是否是预期状态。

这3个类对应整个http请求的3个核心步骤。请求、处理、返回。

2.2 一次完整的http请求以及处理流程

主要通过MockMvc对象。

使用分步构造对象,不使用链式调用,阅读不直观,且常包含中文,虽然不建议肉眼打印中文进行测试判断,但是有时候还是需要。

反例:

mockMvc.perform(post(url)
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .header(TestConstant.HEADER_TOKEN, TestConstant.USER_ADMIN_TOKEN)
        .content(jacksonMapper.writeValueAsString(vo))
)
        .andExpect(status().isOk())
        .andDo(print());

推荐

String url = BASE_URL + "/abc";

// 第一步,构建request
MockHttpServletRequestBuilder request = post(url).contentType(MediaType.APPLICATION_JSON_VALUE)
        .header(TestConstant.HEADER_TOKEN, TestConstant.USER_ADMIN_TOKEN)
        .content(jacksonMapper.writeValueAsString(new ArraList()));

// 执行请求
ResultActions perform = super.mockMvc.perform(request);

// 设置返回数据编码
// 设置response编码,防止print时中文乱码。默认是iso-8859-1。
perform.andReturn().getResponse().setCharacterEncoding("utf-8");

// 对响应的数据进行判断
perform.andExpect(status().isOk())
        .andDo(print());

2.3 MockMvcRequestBuilders

参考代码

2.4 MockMvcResultMatchers

参考代码

2.5 MockMvcResultHandlers

参考代码

3 总结

实质上就是一次http请求,等同于postman、浏览器等测试工具,只不过更优的是进行代码化,利于测试。属于集成测试范畴。