开发环境: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 单元测试的更多相关文章

  1. Spring Boot学习——单元测试

    本随笔记录使用Spring Boot进行单元测试,主要是Service和API(Controller)进行单元测试. 一.Service单元测试 选择要测试的service类的方法,使用idea自动创 ...

  2. Spring Boot干货系列:(十二)Spring Boot使用单元测试(转)

    前言这次来介绍下Spring Boot中对单元测试的整合使用,本篇会通过以下4点来介绍,基本满足日常需求 Service层单元测试 Controller层单元测试 新断言assertThat使用 单元 ...

  3. Spring Boot 的单元测试

    Spring Boot 的单元测试 引入依赖 testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-tes ...

  4. Spring Boot使用单元测试

    一.Service层单元测试: 代码如下: package com.dudu.service;import com.dudu.domain.LearnResource;import org.junit ...

  5. 学习 Spring Boot:(二十九)Spring Boot Junit 单元测试

    前言 JUnit 是一个回归测试框架,被开发者用于实施对应用程序的单元测试,加快程序编制速度,同时提高编码的质量. JUnit 测试框架具有以下重要特性: 测试工具 测试套件 测试运行器 测试分类 了 ...

  6. Spring Boot Mock单元测试学习总结

    单元测试的方法有很多种,比如使用Postman.SoapUI等工具测试,当然,这里的测试,主要使用的是基于RESTful风格的SpringMVC的测试,我们可以测试完整的Spring MVC流程,即从 ...

  7. Spring Boot 的单元测试和集成测试

    学习如何使用本教程中提供的工具,并在 Spring Boot 环境中编写单元测试和集成测试. 1. 概览 本文中,我们将了解如何编写单元测试并将其集成在 Spring Boot 环境中.你可在网上找到 ...

  8. (27)Spring Boot Junit单元测试【从零开始学Spring Boot】

    Junit这种老技术,现在又拿出来说,不为别的,某种程度上来说,更是为了要说明它在项目中的重要性. 那么先简单说一下为什么要写测试用例 1. 可以避免测试点的遗漏,为了更好的进行测试,可以提高测试效率 ...

  9. (转)Spring Boot Junit单元测试

    场景:在项目开发中要测试springboot工程中一个几个dao和service的功能是否正常,初期是在web工程中进行要素的录入,工作量太大.使用该单元测试大大减小了工作强度. Junit这种老技术 ...

随机推荐

  1. 解决Android调用相机拍照,要报“打开相机失败”查看debug日志显示“setParameters failed”的问题

    使用CameraLibrary项目,在部分手机或平板上不能正常使用,要报“打开相机失败”查看debug日志显示“setParameters failed”. 找到CameraView.java中的se ...

  2. 轻松玩转windows之redis实战

    Redis是一个常用的键值对数据库.本篇分享一下如何轻松在睿江云上实现基于windows的redis开发环境. 1. 登录睿江云 点击右上角登录框 ​ 进入登录页面,输入账号密码登录 ​ 进入控制台, ...

  3. 【STM32-V6】STM32F429BIT6开发板开源, 丰富软件资源, 强劲硬件配置, 配套400多实例, 9套手册持续更新中2019-12-12

    淘宝购买地址:淘宝购买链接 次.当前标准库最新版本V2.3,HAL库最新版本V1.1 安富莱微信公共平台,欢迎大家关注(打造高质量公众号) 新版用户手册,重在BSP驱动包设计方法,HAL库的框架学习, ...

  4. React的setState学习及应用

    React的setState学习及应用 一:作用: setState() 将对组件 state 的更改排入队列,并通知 React 需要使用更新后的 state 重新渲染此组件及其子组件.这是用于更新 ...

  5. 【转载】ssh-copy-id三步实现SSH无密码登录和ssh常用命令

      ssh-keygen  产生公钥与私钥对 ssh-copy-id 将本机的公钥复制到远程机器的authorized_keys文件中,ssh-copy-id也能让你有到远程机器的home, ~./s ...

  6. 三个月前的评测拖延三个月仍旧是拳王No.1吗?YES!

    距前作展开隐形的翅膀,WPR003N补完篇仿佛已经隔了几个光年,最近替换了2019发现android sdk需要手冻放入一个tools2文件夹来延续Eclipse style的m$ distribut ...

  7. Computer: Use the mouse to open the analog keyboard

    Xx_Introduction Please protection,respect,love,"China's Internet Security Act"! For learni ...

  8. 20190608_浅谈go&java差异(三)

    20190608_浅谈go&java差异(三) 转载请注明出处https://www.cnblogs.com/funnyzpc/p/10990703.html 第三节内容概览 多线程通讯(线程 ...

  9. pyecharts绘制地图

    python 绘制地图 环境准备 1.1 安装必备绘画库 亲身体验,最新版的pyecharts使用不来,通过百度寻得的教学推荐版本 0.1.9.4 可以绘制完成世界地图,国家地图以及市级地图,但是不能 ...

  10. varnish实现缓存加速

    varnish实现缓存加速 一.采用varnish为nginx实现缓存加速1.实验环境:(1)一台varnish缓存服务器,一台nginx服务器(2)关闭防火墙和selinux2.配置varnish( ...