SpringBoot MockMvc

1 添加依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>

<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.13.2</version>
	<scope>test</scope>
</dependency>

2 MockMvc 介绍

MockMvc 是 Spring 测试框架中的一个实用工具类,用于模拟 Web 请求并获取响应结果,以便对 Spring MVC 控制器进行单元测试。它提供了一种更好的方式来测试 Web 层,而不需要启动整个服务器。

使用 MockMvc 的优势 Value
1 不需要启动完整的服务器环境,可以更快地运行测试。
2 可以模拟各种 HTTP 请求和响应场景,包括设置请求头、请求参数、上传文件等。
3 可以直接注入被测试的控制器,而不需要启动整个应用上下文。
4 可以方便地检查响应结果,包括状态码、响应头、响应体等。

3 MockMvc 测试

package com.xu.test;

import cn.hutool.json.JSONUtil;
import com.xu.test.controller.TestController;
import com.xu.test.service.TestService;
import com.xu.test.service.impl.TestServiceImpl;
import jakarta.servlet.http.Cookie;
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.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
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.ResultActions;
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 java.util.HashMap;
import java.util.Map;

@SpringBootTest
@RunWith(SpringRunner.class)
public class MockMvcTest1 {

    private MockMvc mock;

    @Autowired
    private WebApplicationContext wac;

    @Before
    public void setUp() {
        mock = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    public void get() throws Exception {
        ResultActions actions = mock.perform(MockMvcRequestBuilders.get("/test/test1?a=1&b=2")
                        .header("X-Access-Token", "0123456789")
                        .cookie(new Cookie("cookie", "123456789"))
                        .param("a", "1")
                        .param("b", "2"));

        // 期望请求成功
        actions.andExpect(MockMvcResultMatchers.status().isOk());
        // 打印请求头
        actions.andDo(MockMvcResultHandlers.print());

        MvcResult result = actions.andReturn();
        // 断言
        Assert.assertTrue(result.getResponse().isCommitted());
    }

    @Test
    public void post() throws Exception {
        // 请求体
        Map<String, Object> body = new HashMap<>();
        body.put("a", "1");

        // 请求
        ResultActions actions = mock.perform(MockMvcRequestBuilders.post("/test/test2")
                .header("X-Access-Token", "0123456789")
                .header(HttpHeaders.AUTHORIZATION, "0123456789")
                .content(JSONUtil.toJsonPrettyStr(body))
                .param("a", "1")
                .param("b", "2")
                .contentType(MediaType.APPLICATION_JSON_VALUE));

        // 期望返回的是JSON
        actions.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON));
        // 期望返回的a=1
        actions.andExpect(MockMvcResultMatchers.jsonPath("$.a").value(1));
        // 期望请求成功
        actions.andExpect(MockMvcResultMatchers.status().isOk());
        // 打印请求头
        actions.andDo(MockMvcResultHandlers.print());
        // 结果
        MvcResult result = actions.andReturn();
        // 断言
        Assert.assertEquals(MediaType.APPLICATION_JSON_VALUE, result.getResponse().getContentType());
    }

}

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-11 07:50:07       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-11 07:50:07       101 阅读
  3. 在Django里面运行非项目文件

    2024-05-11 07:50:07       82 阅读
  4. Python语言-面向对象

    2024-05-11 07:50:07       91 阅读

热门阅读

  1. 【Redis7】10大数据类型之HyperLogLog类型

    2024-05-11 07:50:07       33 阅读
  2. 概率论学习-笔记1

    2024-05-11 07:50:07       30 阅读
  3. C++语法|可调用对象和函数对象

    2024-05-11 07:50:07       38 阅读
  4. Mysql之SQL Mode问题

    2024-05-11 07:50:07       34 阅读