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这种老技术 ...
随机推荐
- 仿Inshot分享页图片圆形展开缩放动画
版权声明:本文为xing_star原创文章,转载请注明出处! 本文同步自http://javaexception.com/archives/221 圆形展开缩放动画 关键代码: final Anima ...
- Nuxt+Vuex初体验
小呀嘛小二郎,背着书包上学堂... 今天一个困扰了我一周时间的问题终于被我解决了,值得庆祝 在Nuxt中使用Vuex实现数据存储 首先: 在store目录下新建一个index.js文件 需要有两个组件 ...
- 持续集成(CI):Jmeter+Ant+Jenkins定时构建
这里Jenkins的安装部署以及工程项目的整体配置不做赘述,其它博文已经说明,这里主要是赘述Ant的相关配置,build.xml文件配置以及项目中的部分配置 一.build.xml 在Ant的安装目录 ...
- idea自用快捷键(非常实用)
最近看了下idea的快捷键,不禁感慨idea真是太强大了,这里记录一下我常用的快捷键 Ctrl+F:在当前文件中查找 Ctrl+R:替换字符串 Alt + shift + 鼠标点击 多处同时编辑 ...
- 自己总结numpy用法
最近用numpy比较多,边用边自己总结用法. 1. 数组 1.1 生成 m行 * n列 的随机数组 import numpy as np # 生成 m行*n列 的随机数组 # np.random.ra ...
- English:2019100401_Suffix"ery"
Ax_introduction source a Frech mean to "state,quality,act,place where etc" 1)After the ver ...
- 最近几周,写了个微信好友检测助手App
版权声明:本文为xing_star原创文章,转载请注明出处! 本文同步自http://javaexception.com/archives/130 微信好友检测助手App 最近几周,写了个微信好友检测 ...
- Ali 访问控制 RAM 用户身份
Ali 访问控制 RAM 用户身份 2018/11/13 Chenxin 参考: https://help.aliyun.com/product/28625.html?spm=a2c4g.111866 ...
- mysql初始化/usr/local/mysql/bin/mysqld: error while loading shared libraries: libnuma.so.1: cannot open shared object file: No such file or directory
[root@test153 ~]# /usr/local/mysql/bin/mysqld --initialize --user=mysql --basedir=/usr/local/mysql - ...
- ORA-14061: 不能更改索引分区列的数据类型或长度
修改分区表主键时报错: 在行: 2 上开始执行命令时出错 -alter table KC23 modify AAZ210 VARCHAR2(50)错误报告 -SQL 错误: ORA-14061: 不能 ...