当前位置:网站首页>This article explains in detail how mockmvc is used in practical work

This article explains in detail how mockmvc is used in practical work

2022-07-06 14:14:00 Bulst

brief introduction

When performing integration tests on modules , Hope to be able to input URL Yes Controller To test , If by starting the server , establish http client To test , This can make testing very cumbersome , such as , Slow startup speed , It's not convenient to test and verify , Rely on network environment, etc

MockMvc Realized with Http Simulation requested , Can use the form of network directly , The switch to Controller Call to , This makes the test faster 、 Independent of network environment , It also provides a set of verification tools , This makes the verification of the request uniform and convenient

technological process

  1. MockMvcBuilder Instantiation MockMvc
  2. mockMvc call perform, Execute one RequestBuilder request , call controller Business processing logic
  3. perform return ResultActions, Return operation result , adopt ResultActions, Provides a unified way to verify
  4. Use StatusResultMatchers Verify request results
  5. Use ContentResultMatchers Verify the content returned by the request

Code

Here is the complete test case : contain Junit5 as well as Mockmvc

package com.uncle.junittest.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/** * @author * @date 2022-01-27  In the morning 10:30 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    

    /** *  Serial number  */
    private static final long serialVersionUID = -4449140937612137858L;

    /** *  user id */
    private String id;

    /** *  nickname  */
    private String fullName;

    /** *  user name  */
    private String userName;

    /** *  password  */
    private String password;

    /** *  Age  */
    private Integer age;

    /** *  Gender  */
    private String sex;

}
package com.uncle.junittest.mapper;

import com.uncle.junittest.bean.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

/** * @author * @date 2022-01-27  Afternoon 3:30 **/
@Repository
public interface UserMapper {
    

    /** *  Ways to increase users  * * @param user  User information  * @return  Increase success return :1; Otherwise return to :0 */
    @Insert("insert into user values (#{id},#{fullName},#{userName},#{password},#{age},#{sex})")
    int saveUser(User user);

    /** *  according to id Query user information  * * @param id  user id * @return  User information  */
    @Select("select * from user where id = #{id}")
    User getUser(String id);


}
package com.uncle.junittest.service;

import com.uncle.junittest.bean.User;
import org.apache.ibatis.annotations.Select;

/** * @author * @date 2022-01-27  Afternoon 3:29 **/
public interface UserService {
    

    /** *  Ways to increase users  * @param user  User information  * @return  Increase success return :1; Otherwise return to :0 */
    int saveUser(User user);

    /** *  according to id Query user information  * @param id  user id * @return  User information  */
    User getUser(String id);

}
package com.uncle.junittest.service.impl;

import com.uncle.junittest.bean.User;
import com.uncle.junittest.mapper.UserMapper;
import com.uncle.junittest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/** * @author * @date 2022-01-27  Afternoon 3:29 **/
@Service
public class UserServiceImpl implements UserService {
    

    /** * UserMapper object  */
    @Autowired
    private UserMapper userMapper;

    /** *  Ways to increase users  * @param user  User information  * @return  Increase success return :1; Otherwise return to :0 */
    @Override
    public int saveUser(User user) {
     return userMapper.saveUser(user); }

    /** *  according to id Query user information  * @param id  user id * @return  User information  */
    @Override
    public User getUser(String id) {
    
        return userMapper.getUser(id);
    }


}
package com.uncle.junittest.controller;

import com.uncle.junittest.bean.User;
import com.uncle.junittest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/** * @author * @date 2022-01-27  Afternoon 3:29 **/
@RequestMapping("/test")
@RestController
public class UserController {
    

    /** * UserService object  */
    @Autowired
    private UserService userService;


    /** *  New users  * @param user User * @return String */
    @PostMapping("/saveUser")
    public String saveUser(@RequestBody User user) {
    

        int i = userService.saveUser(user);

        return i == 1 ? user.toString() : " Failed to add new user ";
    }

    /** *  Get user information  * * @return String */
    @GetMapping("/getUser/{id}")
    public String getUser(@PathVariable(value = "id") String id) {
    
        User user = userService.getUser(id);
        return user.toString();
    }
}
package com.uncle.junittest;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.uncle.junittest.mapper")
public class JunitTestApplication {
    

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

}

spring:
  datasource:
    username: root
    password: 
    url: jdbc:mysql://@rm-2ze44u6e2z7t924t0xo.mysql.rds.aliyuncs.com:3306/

server:
  port: 80

mybatis:
  configuration:
    map-underscore-to-camel-case: true

package com.uncle.junittest.controller;

import com.alibaba.fastjson.JSON;
import com.uncle.junittest.bean.User;
import lombok.extern.slf4j.Slf4j;
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.HttpHeaders;
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.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;


import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

/** *  User test class  * * @AutoConfigureMockMvc: This annotation will be automatically configured mockMvc Unit test  */
@DisplayName(value = " User test class ")
@Slf4j
@AutoConfigureMockMvc
@SpringBootTest
class UserControllerTest {
    

    /** *  Before each unit test, execute  */
    @BeforeEach
    void testBeforeEach() {
    
        log.info(" The test is about to begin !");
    }

    /** *  After each unit test, execute  */
    @AfterEach
    void testAfterEach() {
    
        log.info(" The test is over !");
    }

    /** *  Perform... Before all tests  */
    @BeforeAll
    static void testBeforeAll() {
    
        log.info(" All the tests !");
    }

    /** *  Execute after all tests  */
    @AfterAll
    static void testAfterAll() {
    
        log.info(" All tests are over !");
    }

    /** * mockmvc */
    @Autowired
    MockMvc mockMvc;

    /** *  Add user interface test  * * @Disabled: This annotation indicates that the test does not need to be started  * @Transactional: Things roll back  */
    @Disabled
    @DisplayName(" Add user interface test ")
    @Transactional
    @Test
    void saveUser() throws Exception {
    

        //  Request address 
        String urlTemplate = "/test/saveUser";

        /*  Request header set  */
        HttpHeaders headers = new HttpHeaders();
        headers.add("header1", "header1");
        headers.add("header2", "header2");

        /*  Parameter body  */
        String uuid = UUID.randomUUID().toString();
        User user = new User();
        user.setId("4");
        user.setFullName("copico");
        user.setUserName("kebike");
        user.setPassword("123456");
        user.setAge(19);
        user.setSex(" Woman ");

        //  convert to json object 
        String jsonString = JSON.toJSONString(user);

        //  request 
        RequestBuilder request = MockMvcRequestBuilders
                // post request 
                .post(urlTemplate)
                //  data type 
                .contentType(MediaType.APPLICATION_JSON)
                //  Request header 
                .headers(headers)
                //  Request body 
                .content(jsonString);

        MvcResult mvcResult = mockMvc.perform(request)
                //  Print log 
                .andDo(print())
                //  Get the return value 
                .andReturn();

        //  Get the status code from the return value 
        int status = mvcResult.getResponse().getStatus();
        // Get the content of the response from the return value 
        String contentAsString = mvcResult.getResponse().getContentAsString();

        //  Assertion 
        assertAll("heading",
                () -> assertEquals(200, status, " Save failed "),
                () -> assertEquals(user.toString(), contentAsString, " Data save failure "));


    }

    /** *  Get user interface test  */
    @DisplayName(" Get user interface test ")
    @Test
    void getUser() throws Exception {
    


        //  Expected results 
        User user = new User("1",
                " Small soft ",
                "neusoft",
                "123456",null,null);

        //  Request address 
        String urlTemplate = "/test/getUser/1";

        /*  Request header set  */
        HttpHeaders headers = new HttpHeaders();
        headers.add("headers1", "headers1");
        headers.add("headers2", "headers2");

        LinkedMultiValueMap<String,String> linkedMultiValueMap = new LinkedMultiValueMap();
        linkedMultiValueMap.add("params1", "params1");
        linkedMultiValueMap.add("params2", "params2");

        //  request 
        RequestBuilder request = MockMvcRequestBuilders
                // post request 
                .get(urlTemplate)
                //  data type 
                .contentType(MediaType.APPLICATION_JSON)
                //  Request header 
                .header("header1","header1")
                .headers(headers)
                //  Request parameters 
                .param("param1","param2")
                .params(linkedMultiValueMap);

        MvcResult mvcResult = mockMvc.perform(request)
                //  Print log 
                .andDo(print())
                //  Get the return value 
                .andReturn();

        //  Get the status code from the return value 
        int status = mvcResult.getResponse().getStatus();
        // Get the content of the response from the return value 
        String contentAsString = mvcResult.getResponse().getContentAsString();

        //  Assertion 
        assertAll("heading",
                () -> assertEquals(200, status, " User information acquisition failed "),
                () -> assertEquals(user.toString(), contentAsString, " Data inconsistency , Acquisition failure "));


    }

    /** * *  Specify the timeout of the method  *  Out of time test exception  * @throws InterruptedException */
    @DisplayName(value = " Out of time test ")
    @Timeout(value = 500,unit = TimeUnit.MILLISECONDS)
    @Test
    void testTimeout() throws InterruptedException {
    
        Thread.sleep(1000);
    }

    /** *  Repeat the test n Time  */
    @RepeatedTest(value = 2)
    void repeatedTest() {
    

        assertArrayEquals(new int[]{
    1, 2}, new int[]{
    1, 2});
    }


}
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.uncle</groupId>
    <artifactId>junit-test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>junit-test</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
<!-- <version>5.1.47</version>-->
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

原网站

版权声明
本文为[Bulst]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131410386733.html