本文主要是介绍Spring Boot学习笔记(二十)Spring Boot MockMvc集成测试,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Spring Boot MockMvc集成测试
Web 测试
- Spring Boot 提供了 MockMvc 工具类,非常方便对 Web 层进行验证,引入了 MockMvc 支持了对Controller 层的测试
数据库
- 数据库:android,数据表 user
新建项目
pom.xml
<?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.2.0.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>wen</groupId><artifactId>mockmvc</artifactId><version>0.0.1-SNAPSHOT</version><name>mockmvc</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><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></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.6</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
其中需要引入的依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><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></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.6</version></dependency></dependencies>
项目结构
配置文件application.properties:
# datasource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/android?userUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone = GMT
spring.datasource.username=root
spring.datasource.password=
# jpa
spring.jpa.database=mysql
# 配置在日志中打印出执行的 SQL 语句信息。
spring.jpa.show-sql=true
# Hibernate 创建数据表的时候,默认的数据库存储引擎选择的是MyISAM。这个参数是在建表的时候,将默认的存储引擎切换为InnoDB用的。
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
# 配置指明在程序启动的时候要删除并且创建实体类对应的表。(不要在生产环境中使用)
spring.jpa.properties.hibernate.hbm2ddl.auto=create
实体类 User.java:
package wen.mockmvc.pojo;import lombok.Data;import javax.persistence.*;
import java.io.Serializable;@Data
@Entity
@Table(name = "user")
public class User implements Serializable {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;@Column(length = 32)private String username;@Column(length = 64)private String password;public User(Long id, String username, String password) {this.id = id;this.username = username;this.password = password;}
}
接口类MockRepository.java:
package wen.mockmvc.repository;import wen.mockmvc.pojo.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;@Repository
public interface MockRepository extends JpaRepository<User, Long> {
}
Service层 MockService.java:
package wen.mockmvc.service;import wen.mockmvc.pojo.User;public interface MockService {User getUser(Long id);void out(Long id);}
实现类MockServiceImpl.java:
package wen.mockmvc.service.impl;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wen.mockmvc.pojo.User;
import wen.mockmvc.repository.MockRepository;
import wen.mockmvc.service.MockService;@Service
public class MockServiceImpl implements MockService {@Autowiredprivate MockRepository mockRepository;@Overridepublic User getUser(Long id) {return mockRepository.findById(id).get();}@Overridepublic void out(Long id) {System.out.println(id);}}
控制类 MockController.java:
package wen.mockmvc.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import wen.mockmvc.pojo.User;
import wen.mockmvc.service.MockService;@RestController
@RequestMapping(value = "mock")
public class MockController {@Autowiredprivate MockService mockService;@GetMapping(value = "user/{id}")public User getUser(@PathVariable Long id) {User user = mockService.getUser(id);return user;}}
测试类 MockControllerTest.java:
package wen.mockmvc;import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import wen.mockmvc.controller.MockController;
import wen.mockmvc.pojo.User;
import wen.mockmvc.service.MockService;import static org.mockito.BDDMockito.any;
import static org.mockito.BDDMockito.given;@RunWith(SpringRunner.class)
@WebMvcTest(MockController.class)
@Slf4j
public class MockControllerTest {@Autowiredprivate MockMvc mockMvc;@MockBeanprivate MockService mockService;@Beforepublic void setUp() {User user = new User(1L, "123", "123");// given方法,调用特定方法时返回特定值时使用given(mockService.getUser(any())).willReturn(user);}/*** 执行流程:* MockMvcRequestBuilders.get() 返回一个MockHttpServletRequestBuilder对象;* MockHttpServletRequestBuilder.param() 添加请求传值,可以带多个参数; (这里并没有使用到)* MockHttpServletRequestBuilder.accept(MediaType.TEXT_HTML_VALUE)) 设置返回类型; (这里并没有使用到)* <p>* mockMvc.perform()方法,执行一个RequestBuilder请求,调用controller的业务处理逻辑,perform()方法返回ResultActions,返回操作结果,通过ResultActions,提供了统一的验证方式;* <p>* ResultActions.andExpect添加执行完成后的断言,验证执行结果是否正确;* ResultActions.andDo添加一个MockMvcResultHandlers结果处理器,表示要对结果做点什么事情,如此处使用MockMvcResultHandlers.print()输出整个响应结果信息;* ResultActions.andReturn表示执行完成后返回相应的结果。** @throws Exception*/@Testpublic void getAuthUser() throws Exception {MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/mock/user/16")).andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn();}
}
测试结果:
项目源码:https://github.com/StephaineWYT/mockmvc
这篇关于Spring Boot学习笔记(二十)Spring Boot MockMvc集成测试的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!