当前位置:网站首页>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】
List of articles
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
- MockMvcBuilder Instantiation MockMvc
- mockMvc call perform, Execute one RequestBuilder request , call controller Business processing logic
- perform return ResultActions, Return operation result , adopt ResultActions, Provides a unified way to verify
- Use StatusResultMatchers Verify request results
- 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>
边栏推荐
- [insert, modify and delete data in the headsong educator data table]
- 小程序web抓包-fiddler
- Force deduction 152 question multiplier maximum subarray
- HackMyvm靶机系列(5)-warez
- 链队实现(C语言)
- 强化学习基础记录
- [dark horse morning post] Shanghai Municipal Bureau of supervision responded that Zhong Xue had a high fever and did not melt; Michael admitted that two batches of pure milk were unqualified; Wechat i
- Detailed explanation of network foundation routing
- Network layer - simple ARP disconnection
- Record an API interface SQL injection practice
猜你喜欢
Callback function ----------- callback
Programme de jeu de cartes - confrontation homme - machine
撲克牌遊戲程序——人機對抗
It's never too late to start. The tramp transformation programmer has an annual salary of more than 700000 yuan
攻防世界MISC练习区(SimpleRAR、base64stego、功夫再高也怕菜刀)
SRC mining ideas and methods
7-5 走楼梯升级版(PTA程序设计)
强化学习基础记录
内网渗透之内网信息收集(二)
浅谈漏洞发现思路
随机推荐
小程序web抓包-fiddler
msf生成payload大全
How to understand the difference between technical thinking and business thinking in Bi?
Brief introduction to XHR - basic use of XHR
【educoder数据库实验 索引】
7-1 输出2到n之间的全部素数(PTA程序设计)
7-5 staircase upgrade (PTA program design)
Hackmyvm target series (2) -warrior
网络层—简单的arp断网
[experiment index of educator database]
Mixlab unbounded community white paper officially released
DVWA (5th week)
7-4 hash table search (PTA program design)
Only 40% of the articles are original? Here comes the modification method
Hackmyvm target series (5) -warez
Xray and Burp linked Mining
7-3 构造散列表(PTA程序设计)
List and data frame of R language experiment III
【数据库 三大范式】一看就懂
Spot gold prices rose amid volatility, and the rise in U.S. prices is likely to become the key to the future