spring boot单元测试之二:用MockMvc为controller做单元测试(spring boot 2.4.3)

一,演示项目的相关信息:

 1,地址:

https://github.com/liuhongdi/controllertest

2,功能:演示用MockMvc为controller做单元测试

3,项目结构:如图:

说明:刘宏缔的架构森林是一个专注架构的博客,

网站:https://blog.imgtouch.com
本文: https://blog.imgtouch.com/index.php/2023/05/26/spring-boot-dan-yuan-ce-shi-zhi-er-yong-mockmvc-wei/

         对应的源码可以访问这里获取: https://github.com/liuhongdi/

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,java代码说明

1,controller/HomeController.java:

复制代码
package com.controllertest.demo.controller;

import com.controllertest.demo.result.RestResult;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/home")
public class HomeController {

    @GetMapping("/home1")
    public String home1() {
        return "1111";
    }
    //get方式登录
    @GetMapping("/loginget")
    public RestResult loginget(@RequestParam(value="username",required = true,defaultValue = "") String username,
                           @RequestParam(value="password",required = true,defaultValue = "") String password) {
        if (username.equals("")) {
            return RestResult.error(1,"failed");
        } else {

            return RestResult.success("success");
        }
    }
    //post方式登录
    @PostMapping("/loginpost")
    public String loginpost(@RequestParam(value="username",required = true,defaultValue = "") String username,
                                @RequestParam(value="password",required = true,defaultValue = "") String password) {
        if (username.equals("")) {
            return "error";
        }else {
            return "success";
        }

    }
}
复制代码

 

2,result/RestResult.java:

复制代码
package com.controllertest.demo.result;

import com.controllertest.demo.constant.ResponseCode;
import java.io.Serializable;


/**
 * @desc: API 返回结果
 * @author: liuhongdi
 * @date: 2020-07-01 11:53
 * return :
 * 0:success
 * not 0: failed
 */
public class RestResult implements Serializable {

    //uuid,用作唯一标识符,供序列化和反序列化时检测是否一致
    private static final long serialVersionUID = 7498483649536881777L;
    //标识代码,0表示成功,非0表示出错
    private Integer code;
    //提示信息,通常供报错时使用
    private String msg;
    //正常返回时返回的数据
    private Object data;

    public RestResult(Integer status, String msg, Object data) {
        this.code = status;
        this.msg = msg;
        this.data = data;
    }

    //返回成功数据
    public static RestResult success(Object data) {
        return new RestResult(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg(), data);
    }

    public static RestResult success(Integer code,String msg) {
        return new RestResult(code, msg, null);
    }

    //返回出错数据
    public static RestResult error(ResponseCode code) {
        return new RestResult(code.getCode(), code.getMsg(), null);
    }
    public static RestResult error(Integer code,String msg) {
        return new RestResult(code, msg, null);
    }

    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }

}
复制代码

 

3,controller/HomeControllerTest.java:

复制代码
package com.controllertest.demo.controller;

import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

import com.jayway.jsonpath.JsonPath;

@AutoConfigureMockMvc
@SpringBootTest
class HomeControllerTest {

    @Autowired
    private HomeController homeController;

    @Autowired
    private MockMvc mockMvc;

    @BeforeAll
    static void initAll() {
        System.out.println("this is BeforeAll");
    }

    @AfterAll
    static void endAll() {
        System.out.println("this is AfterAll");
    }

    @BeforeEach
    public void initOne() {
        System.out.println("this is BeforeEach");
    }

    @AfterEach
    public void endOne() {
        System.out.println("this is AfterEach");
    }

    @Test
    @DisplayName("测试直接返回字符串")
    void home1() throws Exception {
        MvcResult mvcResult = mockMvc.perform(get("/home/home1")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED))
                .andReturn();
        String content = mvcResult.getResponse().getContentAsString();
        assertThat(content, equalTo("1111"));
    }

    @Test
    @DisplayName("测试get方式登录")
    void loginget() throws Exception {
        //使用expect处理json
        MvcResult mvcResult = mockMvc.perform(get("/home/loginget")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED))
                .andExpect(status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.code").value("1"))
                .andExpect(MockMvcResultMatchers.jsonPath("$.msg").value("failed"))
                .andReturn();

        //使用jsonpath处理json,然后用assertThat断言
        mvcResult = mockMvc.perform(get("/home/loginget")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("username","laoliu")
                .param("password","aaa"))
                .andExpect(status().isOk())
                //.andExpect(MockMvcResultMatchers.jsonPath("$.code").value("0"))
                //.andExpect(MockMvcResultMatchers.jsonPath("$.data").value("success"))
                .andReturn();

        String content = mvcResult.getResponse().getContentAsString();
        int code = JsonPath.parse(content).read("$.code");
        assertThat(code, equalTo(0));
        String data = JsonPath.parse(content).read("$.data");
        assertThat(data, equalTo("success"));
    }

    @Test
    @DisplayName("测试post方式登录")
    void loginpost() throws Exception {
        MvcResult mvcResult = mockMvc.perform(post("/home/loginpost")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED))
                .andExpect(status().isOk())
                .andReturn();
        String content = mvcResult.getResponse().getContentAsString();
        assertThat(content, equalTo("error"));

        mvcResult = mockMvc.perform(post("/home/loginpost")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("username","laoliu")
                .param("password","aaa"))
                .andExpect(status().isOk())
                .andReturn();
        content = mvcResult.getResponse().getContentAsString();
        assertThat(content, equalTo("success"));
    }
}
复制代码

 

三,测试效果

1,运行结果:

2,控制台输出:

四,查看spring boot的版本:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.3)

 

posted @   刘宏缔的架构森林  阅读(693)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
历史上的今天:
2020-03-01 docker的常用操作之二:docker内无法解析dns之firewalld设置等
2020-03-01 centos8安装fastdfs6.06集群方式三之:storage的安装/配置/运行
2020-03-01 centos8安装fastdfs6.06集群方式二之:tracker的安装/配置/运行
2020-03-01 centos8安装fastdfs6.06集群方式一之:软件下载与安装
2020-03-01 fastdfs之同一台storage server下包含多个store path
2020-03-01 centos8安装fastdfs6.06(单机方式)
点击右上角即可分享
微信分享提示