MockMVC的使用

前言

  1. MockMVC 作用,请求 Controller 层是否正常,替代了 Postman 的作用
  2. 本文,复制黏贴即可使用,包含四种常见情况 Get 提交 params 和 pathvariable 、Post 提交 json 和 from

步骤讲解

  1. 参考大佬博客。
  2. pom 依赖。引入项目需要的所有包
  3. Main 启动类。SpringBoot 的启动类。
  4. Controller 层。提供HTTP接口。
  5. Entity 类。配合封装对象使用。
  6. 单元测试。MockMVC 就是在单元测试中使用。
  7. 注意。注意事项点。

0. 参考大佬博客

  1. https://juejin.cn/post/6844903924248346637

1. pom 依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Spring-mock</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--单元测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.14.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-inline</artifactId>
            <version>3.2.4</version>
            <scope>test</scope>
        </dependency>

        <!-- fastjson  -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2. Main 启动类

package com.jtfr;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootMain {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootMain.class, args);
    }
}

3. Controller 层

package com.jtfr.controller;

import com.jtfr.entity.User;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/test")
public class TestController {

    /**
     * Get 请求, params 参数提交
     * @param a
     * @param b
     * @return
     */
    @GetMapping(value = "/get")
    public String getParams(String a, String b) {
        return "TestController" + a + b;
    }

    /**
     * Get 请求, @Pathvariable 路径参数提交
     * @param page
     * @param size
     * @param name
     * @return
     */
    @GetMapping(value = "/get/{page}/{size}")
    public String getPathVariable(@PathVariable String page, @PathVariable String size, String name) {
        return "TestController" + page + size+ name;
    }

    /**
     * post 请求,json 数据提交
     * @param user
     * @return
     */
    @PostMapping("/postJson")
    public String postJson(@RequestBody User user){
        return "TestController:postJson:"+user.toString();
    }

    /**
     * post 请求,from 数据提交
     * @param user
     * @return
     */
    @PostMapping("/postFrom")
    public String postFrom(User user){
        return "TestController:postFrom:"+user.toString();
    }

}

4. Entity 类

package com.jtfr.entity;

public class User {

    private String id;

    private String username;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", username='" + username + '\'' +
                '}';
    }
}

5. 单元测试(重点)

package com.jtfr.controller;

import com.alibaba.fastjson.JSON;
import com.jtfr.SpringBootMain;
import com.jtfr.entity.User;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
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.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.net.URI;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootMain.class)
public class TestControllerTest extends AbstractTestNGSpringContextTests {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @BeforeClass
    public void before(){
        mockMvc= MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }


    /**
     * Get 请求, params 参数提交
     * @throws Exception
     */
    @Test
    public void mockGet() throws Exception {
        // get请求
        ResultActions ra = mockMvc.perform(MockMvcRequestBuilders
                .get(new URI("/test/get"))
                .param("a", "1")
                .param("b", "2"));
        MvcResult result = ra.andReturn();
        System.out.println("result: " + result.getResponse().getContentAsString());
        Thread.sleep(1000);
    }

    /**
     * Get 请求, @Pathvariable 路径参数提交
     * @throws Exception
     */
    @Test
    public void mockGetPathvariable() throws Exception {
        // get请求
        ResultActions ra = mockMvc.perform(MockMvcRequestBuilders
                .get(new URI("/test/get/1/10"))
                .param("name", "xyyz"));
        MvcResult result = ra.andReturn();
        System.out.println("result: " + result.getResponse().getContentAsString());
        Thread.sleep(1000);
    }

    /**
     * post 请求,json 数据提交
     * @throws Exception
     */
    @Test
    public void mockPost() throws Exception {
        User user = new User();
        user.setId("1");
        user.setUsername("xyz");
        String userJsonStr = JSON.toJSONString(user);
        ResultActions ra = mockMvc.perform(MockMvcRequestBuilders
                .post(new URI("/test/postJson"))
                .content(userJsonStr)
                .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
        );
        MvcResult result = ra.andReturn();
        System.out.println("result: " + result.getResponse().getContentAsString());
        Thread.sleep(1000);
    }


    /**
     * post 请求,from 数据提交
     * @throws Exception
     */
    @Test
    public void mockFrom() throws Exception {
        ResultActions ra = mockMvc.perform(MockMvcRequestBuilders
                .post(new URI("/test/postFrom"))
                .param("id", "2")
                .param("username", "jtfr")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
        );
        MvcResult result = ra.andReturn();
        System.out.println("result: " + result.getResponse().getContentAsString());
        Thread.sleep(1000);
    }
}

6. 注意

  1. import 依赖需要是 testng 的包
  2. 有问题就百度,百度最快解决,其次问关系好的同事。
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页