Spring Boot 2 单元测试
开发环境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8
IDEA新建一个Spring Boot项目后,pom.xml默认包含了Web应用和单元测试两个依赖包。
如下:
<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>
</dependencies>
一、测试Web服务
1、新建控制器类 HelloController.java
package com.example.demo.controller; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class HelloController {
@RequestMapping("/")
public String index() {
return "index";
} @RequestMapping("/hello")
public String hello() {
return "hello";
}
}
2、新建测试类 HelloControllerTest.cs
下面WebEnvironment.RANDOM_PORT会启动一个真实的Web容器,RANDOM_PORT表示随机端口,如果想使用固定端口,可配置为
WebEnvironment.DEFINED_PORT,该属性会读取项目配置文件(如application.properties)中的端口(server.port)。
如果没有配置,默认使用8080端口。
package com.example.demo.controller; import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerTest { @Autowired
private TestRestTemplate restTemplate; @Test
public void testIndex(){
String result = restTemplate.getForObject("/",String.class);
Assert.assertEquals("index", result);
} @Test
public void testHello(){
String result = restTemplate.getForObject("/",String.class);
Assert.assertEquals("Hello world", result);//这里故意写错
}
}
在HelloControllerTest.java代码中右键空白行可选择Run 'HelloControllerTest',测试类里面所有方法。
(如果只想测试一个方法如testIndex(),可在testIndex()代码上右键选择Run 'testIndex()')
运行结果如下,一个通过,一个失败。

二、模拟Web测试
新建测试类 HelloControllerMockTest.java
设置WebEnvironment属性为WebEnvironment.MOCK,启动一个模拟的Web容器。
测试方法中使用Spring的MockMvc进行模拟测试。
package com.example.demo.controller; import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
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 java.net.URI; @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)//MOCK为默认值,也可不设置
@AutoConfigureMockMvc
public class HelloControllerMockTest {
@Autowired
private MockMvc mvc; @Test
public void testIndex() throws Exception{
ResultActions ra = mvc.perform(MockMvcRequestBuilders.get(new URI("/")));
MvcResult result = ra.andReturn();
System.out.println(result.getResponse().getContentAsString());
} @Test
public void testHello() throws Exception{
ResultActions ra = mvc.perform(MockMvcRequestBuilders.get(new URI("/hello")));
MvcResult result = ra.andReturn();
System.out.println(result.getResponse().getContentAsString());
}
}
右键Run 'HelloControllerMockTest',运行结果如下:

三、测试业务组件
1、新建服务类 HelloService.java
package com.example.demo.service; import org.springframework.stereotype.Service; @Service
public class HelloService {
public String hello(){
return "hello";
}
}
2、新建测试类 HelloServiceTest.java
WebEnvironment属性设置为NONE,不会启动Web容器,只启动Spring容器。
package com.example.demo.service; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class HelloServiceTest {
@Autowired
private HelloService helloService; @Test
public void testHello(){
String result = helloService.hello();
System.out.println(result);
}
}
右键Run 'HelloServiceTest',运行结果如下:

四、模拟业务组件
假设上面的HelloService.cs是操作数据库或调用第三方接口,为了不让这些外部不稳定因素影响单元测试的运行结果,可使用mock来模拟
某些组件的返回结果。
1、新建一个服务类 MainService.java
里面的main方法会调用HelloService的方法
package com.example.demo.service; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service
public class MainService {
@Autowired
private HelloService helloService; public void main(){
System.out.println("调用业务方法");
String result = helloService.hello();
System.out.println("返回结果:" + result);
}
}
2、新建测试类 MainServiceMockTest.java
下面代码中,使用MockBean修饰需要模拟的组件helloService,测试方法中使用Mockito的API模拟helloService的hello方法返回。
package com.example.demo.service; import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.BDDMockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@SpringBootTest
public class MainServiceMockTest {
@MockBean
private HelloService helloService;
@Autowired
private MainService mainService; @Test
public void testMain(){
BDDMockito.given(this.helloService.hello()).willReturn("hello world");
mainService.main();
}
}
右键Run 'MainServiceMockTest',运行结果如下:

五、IDEA项目结构图

Spring Boot 2 单元测试的更多相关文章
- Spring Boot学习——单元测试
本随笔记录使用Spring Boot进行单元测试,主要是Service和API(Controller)进行单元测试. 一.Service单元测试 选择要测试的service类的方法,使用idea自动创 ...
- Spring Boot干货系列:(十二)Spring Boot使用单元测试(转)
前言这次来介绍下Spring Boot中对单元测试的整合使用,本篇会通过以下4点来介绍,基本满足日常需求 Service层单元测试 Controller层单元测试 新断言assertThat使用 单元 ...
- Spring Boot 的单元测试
Spring Boot 的单元测试 引入依赖 testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-tes ...
- Spring Boot使用单元测试
一.Service层单元测试: 代码如下: package com.dudu.service;import com.dudu.domain.LearnResource;import org.junit ...
- 学习 Spring Boot:(二十九)Spring Boot Junit 单元测试
前言 JUnit 是一个回归测试框架,被开发者用于实施对应用程序的单元测试,加快程序编制速度,同时提高编码的质量. JUnit 测试框架具有以下重要特性: 测试工具 测试套件 测试运行器 测试分类 了 ...
- Spring Boot Mock单元测试学习总结
单元测试的方法有很多种,比如使用Postman.SoapUI等工具测试,当然,这里的测试,主要使用的是基于RESTful风格的SpringMVC的测试,我们可以测试完整的Spring MVC流程,即从 ...
- Spring Boot 的单元测试和集成测试
学习如何使用本教程中提供的工具,并在 Spring Boot 环境中编写单元测试和集成测试. 1. 概览 本文中,我们将了解如何编写单元测试并将其集成在 Spring Boot 环境中.你可在网上找到 ...
- (27)Spring Boot Junit单元测试【从零开始学Spring Boot】
Junit这种老技术,现在又拿出来说,不为别的,某种程度上来说,更是为了要说明它在项目中的重要性. 那么先简单说一下为什么要写测试用例 1. 可以避免测试点的遗漏,为了更好的进行测试,可以提高测试效率 ...
- (转)Spring Boot Junit单元测试
场景:在项目开发中要测试springboot工程中一个几个dao和service的功能是否正常,初期是在web工程中进行要素的录入,工作量太大.使用该单元测试大大减小了工作强度. Junit这种老技术 ...
随机推荐
- Android 日期对话框 DatePickerDialog
private int year; private int monthOfYear; private int dayOfMonth; @Override protected void onCreate ...
- MSSQL - 最佳实践 - 使用SSL加密连接
MSSQL - 最佳实践 - 使用SSL加密连接 author: 风移 摘要 在SQL Server安全系列专题月报分享中,往期我们已经陆续分享了:如何使用对称密钥实现SQL Server列加密技术. ...
- 利用keras自带房价数据集进行房价预测
import numpy as np from keras.datasets import boston_housing from keras import layers from keras imp ...
- Mysql的安装、配置、优化
Mysql的安装.配置.优化 安装步骤 1.先单击中的安装文件,如果是win7系统,请选择以管理员的方式运行. 2.大概需要30秒的时间,开始进入安装界面.请先把标红的打勾,好进行下一步的动作. 3. ...
- STL常用结构与方法简明总结
C++常用的数据结构 序列式容器 vector(向量.有序数列),list(双向链表),deque(双端队列) 适配器容器 stack(栈),queue(队列) 关联式容器 map(映射.键值对二叉树 ...
- 本地的个人web网站上线的全过程,供大家参考(PHP,简易的LAMP环境搭建)
一 : 你需要准备的东西 1.本地能访问的网站,最好是改过host文件和apache的httpd-vhosts.conf,配置过本地域名的那种(减少传到线上出现的问题,文件路径不对呀啥的) 2.一个云 ...
- Linux下设置mysql允许远程连接
最近在Linux上安装了Mysql,然后在Windows环境下通过Navicat来连接时,出现报错:1045 Access denied for user 'root'@'XXX' (using pa ...
- C# WinForm界面美化--使用IrisSkin实现换肤功能
WinForm界面使用IrisSkin,可以说做到了一键美化,当然美化的效果仁者见仁智者见智,可以挑选自己喜欢的. 1.IrisSkin下载地址:https://www.cr173.com/soft/ ...
- Lucene&Solr框架之第三篇
1.SolrCore的配置 a)schma.xml文件 b)配置中文分析器 2.配置业务域和批量索引导入 a)配置业务域 b)批量索引导入 c)Solrj复杂查询(用Query页面复杂查询.用程序实现 ...
- Windows CLI命令
目录 Windows CLI命令 1.背景 2.netstat 罗列端口号占用情况 3.telnet 远端IP的某个端口号 Windows CLI命令 1.背景 在Windows操作系统下开发,需要用 ...