Unit testing of Controllers is a capability natively supported by the Spring Framework, which simulates an HTTP client initiating a request to a service address and allows testing of the interface without the use of external tools such as Postman.

Specifically, the implementation is provided by the spring-test module of the Spring Framework, see MockMvc.

The following section details how to use the MockMvc test framework to implement unit tests for “Spring Controller”, based on the Spring Boot development framework for validation.

Adding test framework dependencies.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<!-- Spring框架 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
!<-- Spring测试框架 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<!-- 文件操作工具 -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

Importing Static Tool Methods

In order to make it easier to directly call the static methods that come with the test framework when writing test cases, you first need to import these static tool methods.

The static methods to be imported are as follows.

1
2
3
4
5
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
import static org.springframework.test.web.servlet.setup.SharedHttpSessionConfigurer.*;

Initialize MockMvc

There are 2 ways to initialize MockMvc. way 1: explicitly specify the “Controller” class to be tested for configuration Way 2: Configuration based on the Spring container, including the Spring MVC environment and all “Controller” classes, which is usually used.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@SpringBootTest
public class TestControllerTest {

    MockMvc mockMvc;

    // 初始化MockMvc
    @BeforeEach
    void setUp(WebApplicationContext wac) {
        // 方式1:明确指定需要测试的"Controller"类
        this.mockMvc = MockMvcBuilders.standaloneSetup(new TestController()).build();

        // 方式2:基于Spring容器进行配置,包含了Spring MVC环境和所有"Controller"类。
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }
}

In addition, global configuration of MockMvc is available.

1
2
3
4
5
6
7
// 全局配置MockMvc
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
        .defaultRequest(get("/").accept(MediaType.APPLICATION_JSON)) // 默认请求路径
        .apply(sharedHttpSession()) // 配置session
        .alwaysExpect(status().isOk()) // 预期响应状态码
        .alwaysExpect(content().contentType("application/json;charset=UTF-8")) // 预期内容类型
        .build();

Execute tests

MockMvc supports testing of common HTTP methods such as GET, POST, PUT, DELETE, etc. It even supports file upload requests.

Test GET interface

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 访问GET接口:不带参数
@Test
public void testSimpleGet() throws Exception {
    MvcResult result = this.mockMvc.perform(get("/test/simple/get")
            .accept(MediaType.APPLICATION_JSON)) // 接受JSON格式响应消息
            .andReturn(); // 获取返回结果
    Assertions.assertEquals("OK", result.getResponse().getContentAsString());
}

// 访问GET接口:带URL参数
@Test
public void testParamGet() throws Exception {
    int id = 10;
    // 方式1:在URI模板中指定参数
    //MvcResult result = this.mockMvc.perform(get("/test/param/get?id={id}", id).accept(MediaType.APPLICATION_JSON)).andReturn();

    // 方式2:通过param()方法指定参数
    //MvcResult result = this.mockMvc.perform(get("/test/param/get").param("id", String.valueOf(id)).accept(MediaType.APPLICATION_JSON)).andReturn();

    // 方式3:通过queryParam()方法指定参数
    MvcResult result = this.mockMvc.perform(get("/test/param/get").queryParam("id", String.valueOf(id)).accept(MediaType.APPLICATION_JSON)).andReturn();
    Assertions.assertEquals("OK: " + id, result.getResponse().getContentAsString());
}

Testing the POST interface

 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
// 传递表单参数
@Test
public void testSimplePost() throws Exception {
    int id = 10;

    // 调用param()方法传递参数
    MvcResult result = this.mockMvc.perform(post("/test/simple/post")
            .param("id", String.valueOf(id))
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .accept(MediaType.APPLICATION_JSON))
            .andReturn();
    Assertions.assertEquals("{\"id\":10}", result.getResponse().getContentAsString());
}

// 传递JSON参数
@Test
public void testSimplePostJson() throws Exception {
    // 调用content()方法传递json字符串参数
    Subject subject = new Subject();
    subject.setId(10);
    String content = JSON.toJSONString(subject);
    MvcResult result = this.mockMvc.perform(post("/test/simple/post/json")
            .content(content)
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON))
            .andReturn();
    Assertions.assertEquals("{\"id\":10}", result.getResponse().getContentAsString());
}

Test file upload

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
@Test
public void testFileUploadSingle() throws Exception {
    File file = new File("C:\\Users\\xxx\\Downloads\\test.jpg");
    String fileName = FilenameUtils.getName(file.getName());
    byte[] bytes = FileUtils.readFileToByteArray(file);
    MockMultipartFile mockMultipartFile = new MockMultipartFile("file", fileName, MediaType.MULTIPART_FORM_DATA_VALUE, bytes);
    this.mockMvc.perform(multipart("/test/upload/single").file(mockMultipartFile))
                .andExpect(status().isOk())
                .andExpect(content().string("OK"))
                .andDo(print());
}

Define the expected result

When asserting the response result, there are 2 ways.

  1. Use the Assert assertion tool provided by JUnit to determine the return result , which is a very common and common way .
  2. In the MockMvc framework you can define one or more expected results through the andExpect() method, when one of the expected results assertion fails, it will not assert other expected values .
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// 使用Junit断言工具判断返回结果是否符合预期
@Test
public void testAssertResult() throws Exception {
    MvcResult result = this.mockMvc.perform(get("/test/simple/get").accept(MediaType.APPLICATION_JSON)).andDo(print()).andReturn();
    Assert.assertEquals("OK", result.getResponse().getContentAsString());
}

// 在MockMvc框架中定义预期结果
@Test
public void testExpectations() throws Exception {
    this.mockMvc.perform(get("/test/simple/get").accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())        // 预期响应状态码为200
            .andExpect(content().string("OK")) // 预期返回值为字符串“OK”
            .andDo(print());
}

It is more concise to define the expected result for assertion checking directly in the MockMvc framework than to use Junit’s assertion tool to determine the returned result.

Write at the end

Using MockMvc, the testing framework provided by Spring, makes it very easy to implement unit tests for HTTP service interfaces. Instead of leaving all the basic functional verification work to the testers, you should ensure the stability of your code iterations through unit tests.

Reference https://www.cnblogs.com/nuccch/p/15901976.html