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这种老技术 ...
随机推荐
- vue集成cesium,webgis平台第一步(附源码下载)
vue-cesium-platform Vue结合Cesium的web端gis平台 初步效果 笔记本性能限制,运行Cesium温度飙到70度以上.所以平时开发时先开发界面,之后加载Cesium地球 当 ...
- idea上传项目到github
1.在上传项目之前需要先在idea中确认两个配置,一个是git的执行位置,电脑上没有安装git的需要提前安装(下载git软件并且安装,非github desktop),安装之后再idea的settin ...
- Mysql—mysqladmin 命令详解
mysqladmin是一个执行管理操作的客户端程序.它可以用来检查服务器的配置和当前状态.创建和删除数据库等. mysqladmin工具的使用格式:mysqladmin [option] comman ...
- 爬取b站互动视频信息
首先分辨视频是不是互动视频可以看 https://api.bilibili.com/x/player.so?id=cid:1&aid=89017 这个api返回的xml中的 <inter ...
- openssl 证书请求和签名命令req基本分析
一 基本概念: OpenSSL 是一个开源项目,其组成主要包括一下三个组件: openssl:多用途的命令行工具 libcrypto:加密算法库 libssl:加密模块应用库,实现了ssl及tls o ...
- IT兄弟连 HTML5教程 CSS3属性特效 圆角
传统的圆角生成方案,必须使用多张图片作为背景图案.CSS3的出现,使得我们再也不必浪费时间去制作这些图片了,只需要border-radius属性,支持浏览器IE 9.Opera 10.5.Safari ...
- Angular常用VSCode插件
1.Angular 8 Snippets(全家桶) 2.TSLint(ts代码规范.错误提示) 3.Material Icon Theme(文件图标) 4.One Dark Pro(主题) 5.Ang ...
- 分享几个好看又实用的PPT网站~
一,优品PPT[http://www.ypppt.com/] 一个有情怀的免费PPT模板下载网站!拥有非常多很精美的PPT模板,分类齐全,我们可以选择自己喜欢的PPT模板下载套用就可以了. 二,扑奔P ...
- QGIS 3.4 3.6 另存栅格图层到GeoPackage出现覆盖问题 解决方案
转载请声明:博客园 @秋意正寒 升级你的QGIS到3.8或以上 这在3.4.x和3.6.x都存在同样的问题.在老版本QGIS重,如果新建一个GeoPackage,先存入栅格数据就没有这个问题,但是如果 ...
- LeetCode刷题191123
博主渣渣一枚,刷刷leetcode给自己瞅瞅,大神们由更好方法还望不吝赐教.题目及解法来自于力扣(LeetCode),传送门. 算法: 给出一个区间的集合,请合并所有重叠的区间. 示例 1: 输入: ...