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

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

 1,地址:

https://github.com/liuhongdi/controllertest

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

3,项目结构:如图:

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: 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)
原文地址:https://www.cnblogs.com/architectforest/p/14463476.html