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这种老技术 ...
随机推荐
- monkey测试跑多个apk|monkey命令
1.如何跑多个apk的monkey? 黑名单:执行除了黑名单中以外的apk: 白名单:只执行在白名单中的apk. 黑名单的设置方法: a.创建一个名称为blacklist的txt文档,在文件中输入应用 ...
- ShowDoc速记
编写文档好工具showdoc部署 参考:https://www.showdoc.cc/ 一定要看,一定要用卷,丢失数据的痛苦,痛何如哉. https://www.cnblogs.com/harrych ...
- java中线程的几种实现方式
1. 继承Thread类来实现 class MyThread extends Thread{ @Override public void run() { System.out.println(&quo ...
- 在使用Vue2.0中使用axios库时,遇到415错误
解决办法:在axios的第三个参数config中,设置请求头信息'Content-Type': 'application/json;charset=UTF-8' this.$http.post('re ...
- 6.Ansible Roles角色实战
==Roles小技巧:== 1.创建roles目录结构,手动或使用ansible-galaxy init test roles 2.编写roles的功能,也就是tasks. nginx rsyncd ...
- VUE组件 之 Drawer 抽屉
注:因为项目中用的是 element-ui 框架,而这个框架并没有抽屉组件,所以自己实现一个. 一.源码地址 https://github.com/imxiaoer/DrawerForVue 二.效果 ...
- django 做 migrate 时 表已存在的处理
在开发web的时候,如果是以前已存在的项目,项目下载下来后,为了使用测试库的数据,会直接将整个测试库(如sqlite3)拿到本机来.这种情况下,如果执行的顺序不对,很容易在执行migrate的时候出现 ...
- 每日JAVA面试
- react官方脚手架添加less配置
装两个包 npm install --save less less-loader 在node-modules/react-scripts/config/webpack.config.js中 在大概58 ...
- java基础 - 泛型的使用
泛型的使用方式有泛型类,泛型接口,泛型方法. 泛型的意思是把参数类型也当成参数传入,也就是在使用时(类实例化或调用方法时)传入类型. 泛型类 在实例化时传入参数类型,不能对泛型类使用instancec ...