百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

SpringBoot单元测试之一:基本操作

ztj100 2025-01-14 19:11 50 浏览 0 评论

欢迎访问我的GitHub

https://github.com/zq2599/blog_demos

内容:所有原创文章分类和汇总,及配套源码,涉及Java、Docker、Kubernetes、DevOPS等;

关于《SpringBoot单元测试》系列

《SpringBoot单元测试》系列旨在通过一系列知识归纳和实战,和读者们一起提升在SpringBoot环境下的单元测试的技能;

本篇概览

本文是《SpringBoot单元测试》系列的第一篇,咱们一起来写几个最简单的单元测试类,了解如何测试Service层和Controller层,包括以下内容:

  1. 版本和环境信息
  2. 创建《SpringBoot单元测试》系列所有源码的父工程junitpractice
  3. 创建本文实战用到的子工程simplebean
  4. 借助IDEA,对指定java类生成单元测试代码
  5. 测试SpringBoot项目的Service层
  6. 测试SpringBoot项目的Controller层,此时模拟web环境,并未启动web server
  7. 测试SpringBoot项目的Controller层,真正启动web server,用WebTestClient实例发送请求,此时pom.xml中要添加webflux的依赖
  8. 测试SpringBoot项目的Controller层,真正启动web server,用TestRestTemplate实例发送请求
  • 可见上述内容都是些最基本的操作,有助于咱们快速掌握如何编写单元测试用例;

版本和环境信息

整个系列的编码和执行在以下环境进行,供您参考:

  1. 硬件配置:处理器i5-8400,内存32G,硬盘128G SSD + 500G HDD
  2. 操作系统:Windows10家庭中文版
  3. IDEA:2020.2.2 (Ultimate Edition)
  4. JDK:1.8.0_181
  5. SpringBoot:2.3.4.RELEASE
  6. JUnit Jupiter:5.6.2
  • 接下来开始实战,咱们先建好SpringBoot项目;

关于lombok

为了简化代码,项目中使用了lombok,请您在IDEA中安装lombok插件;

源码下载

如果您不想编码,可以在GitHub下载所有源码,地址和链接信息如下表所示(
https://github.com/zq2599/blog_demos):

  • 这个git项目中有多个文件夹,本章的应用在junitpractice文件夹下,如下图红框所示:
  • junitpractice是父子结构的工程,本篇的代码在simplebean子工程中,如下图:

创建Maven父工程

  1. 为了便于管理整个系列的源码,在此建立名为junitpractice的maven工程,后续所有实战的源码都作为junitpractice的子工程;
  2. junitpractice的pom.xml如下,可见是以SpringBoot的2.3.4.RELEASE版本作为其父工程:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <modules>
        <module>simplebean</module>
        <!--
        <module>testenvironment</module>
        -->
    </modules>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.bolingcavalry</groupId>
    <artifactId>junitpractice</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.16.16</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

本篇的源码工程

  • 创建名为simplebean的子工程,pom.xml如下,注意单元测试要依赖spring-boot-starter-test:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.bolingcavalry</groupId>
        <artifactId>junitpractice</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <groupId>com.bolingcavalry</groupId>
    <artifactId>simplebean</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>simplebean</name>
    <description>Demo project for simplebean in Spring Boot junit</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
  • 接下来写一些最简单的代码,让服务能运行起来,service接口:
package com.bolingcavalry.simplebean.service;

public interface HelloService {
    String hello(String name);
}
  • 接口实现:
package com.bolingcavalry.simplebean.service.impl;

import com.bolingcavalry.simplebean.service.HelloService;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

@Service()
public class HelloServiceImpl implements HelloService {
    @Override
    public String hello(String name) {
        return "Hello " + name;
    }
}
  • controller类,调用了HelloService 的服务:
package com.bolingcavalry.simplebean.controller;

import com.bolingcavalry.simplebean.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @Autowired
    private HelloService helloService;

    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    public String logExtend(@PathVariable String name){
        return helloService.hello(name);
    }
}
  • 准备工作完成,可以编写单元测试的代码了;

用IEDA生成单元测试代码

  • 打开HelloServiceImpl.java,如下操作:
  • 在弹出的菜单中选择Test,如下图:
  • 如下图,把红框中的hello方法勾选上:


  • 此时,IDEA会帮我们自动生成单元测试代码,内容和位置如下图所示:
  • 如下图操作,即可执行新增的单元测试代码HelloServiceImplTest.java:
  • 以上就是通过IDEA生成单元测试代码的过程,接下来咱们修改HelloServiceImplTest.java的代码,对SpringBoot工程进行测试;

测试Service层

  • 先来测试工程的Service层,看看HelloService能否正常工作,修改HelloServiceImplTest.java,修改后如下:
@SpringBootTest
class HelloServiceImplTest {
    private static final String NAME = "Tom";

    @Test
    void hello(@Autowired HelloService helloService) {
        TestCase.assertEquals("Hello " + NAME, helloService.hello(NAME));
    }
}
  • 上述代码要注意的是两个注解,第一是SpringBootTest,用于开启springboot对junit的支持(例如指定SpringExtension作为ParameterResolver),第二个是hello方法的入参,通过Autowired取得了Spring容器中的HelloService实例;
  • TestCase.assertEquals方法有两个入参,如果它们的equals比较结果为true,则表示测试通过;
  • 鼠标点击下图红框位置:
  • 在弹出的菜单中,点击Run ‘HelloServiceImplTest’,如下图红框所示:
  • 执行结果如下图所示,测试通过:
  • 新增方法testApplicationContext,用来验证单元测试时能否使用Spring的ApplicationContext实例:
    @Test
    void testApplicationContext(@Autowired ApplicationContext applicationContext) {
        // 通过applicationContext从spring环境取得helloService实例
        HelloService helloService = applicationContext.getBean(HelloService.class);
        // 非空
        TestCase.assertNotNull(helloService);
        // 相等
        TestCase.assertEquals("Hello " + NAME, helloService.hello(NAME));
    }
  • 如下图,可见单元测试时可以使用Spring的ApplicationContext实例来执行spring相关的操作:
  • 对service层进行单元测试的基本操作就完成了,接下来尝试web接口的测试;

测试Controller层(未启动web server)

  • 除了service层,Controller层提供的web接口也是单元测试的重点,接下来尝试最简单的Controller层单元测试;
  • 新建HelloControllerTest.java,内容如下:
package com.bolingcavalry.simplebean.service.impl;

import org.junit.jupiter.api.Test;
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.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
    private static final String NAME = "Tom";
    @Test
    void hello(@Autowired MockMvc mvc) throws Exception {
        // 模拟
        mvc.perform(get("/" + NAME))
                .andExpect(status().isOk())
                .andExpect(content().string("Hello " + NAME));
    }
}
  • 上述代码中,通过AutoConfigureMockMvc注解开启MockMvc的自动装配,再通过MockMvc模拟web环境,在不启动web server的情况下调用到Controller层的服务,再用两个andExpect方法分别验证web服务的返回码和返回内容;
  • 测试通过如下图:

测试Controller层(启动web server)

通过MockMvc的方式调用Controller层的服务时,并没有启动web server,如果我们希望单元测试时web server就像生产环境一样是正常运行的,就不要用MockMvc来模拟web环境,来看看如何在单元测试时将web server启动;

  • SpringBootTest的注解有个属性webEnvironment,其值有以下四种:
MOCK : 模拟的web服务环境,这是默认取值,刚才的HelloControllerTest.java就是这种
RANDOM_PORT : 启动web server,服务端口随机取值
DEFINED_PORT : 启动web server, 服务端口是当前项目设置的端口
NONE : 不提供web服务环境
  • 根据上述定义,新建单元测试类HelloControllerWithWebTestClientTest.java,webEnvironment取值为RANDOM_PORT,这样就能把嵌入式tomcat启动了:
package com.bolingcavalry.simplebean.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.web.reactive.server.WebTestClient;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Slf4j
public class HelloControllerWithWebTestClientTest {

    private static final String NAME = "Tom";

    @Test
    void hello(@Autowired WebTestClient webClient, @LocalServerPort int port) throws Exception {

        webClient
                .get()
                .uri("/" + NAME)
                .exchange()
                .expectStatus()
                .isOk()
                .expectBody(String.class)
                .isEqualTo("Hello " + NAME);

        log.info("web端口是[{}]", port);
    }
}
  • 从上述代码可见,发起请求用的是WebTestClient实例,即从客户端发请求到web server,来验证Controller层的服务;
  • 使用LocalServerPort注解,可以得到服务端口的数值;
  • 使用WebTestClient实例时,pom.xml中一定要添加webflux的依赖,如下:
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-webflux</artifactId>
  <scope>test</scope>
</dependency>
  • 单元测试执行结果如下,红框1证实了嵌入式tomcat已经被启动,红框2就是web监听的端口:

另一种访问web server的方式

  • 刚刚咱们使用WebTestClient来访问web server,但使用WebTestClient必须要在pom.xml中添加webflux的依赖,这个略微有些麻烦,其实您还可以选择TestRestTemplate来取代WebTestClient,而使用TestRestTemplate时无需额外的jar依赖
  • 新建HelloControllerWithTestRestTemplateTest.java,这里面使用TestRestTemplate实例向web server发送请求,另外还展示了assertThat的用法:
package com.bolingcavalry.simplebean.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
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.boot.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Slf4j
public class HelloControllerWithTestRestTemplateTest {

    private static final String NAME = "Tom";

    @Test
    void hello(@Autowired TestRestTemplate testRestTemplate, @LocalServerPort int port) throws Exception {
        log.info("web端口是[{}]", port);
        // 向web server发送请求
        ResponseEntity responseEntity = testRestTemplate.exchange("/" + NAME, HttpMethod.GET, HttpEntity.EMPTY, String.class);
        // 检查code
        assertThat(responseEntity.getStatusCode()).isEqualByComparingTo(HttpStatus.OK);
        // 检查内容
        assertThat(responseEntity.getBody()).isEqualTo("Hello " + NAME);
    }
}
  • 执行单元测试成功:
  • 至此,咱们通过四个简单示例熟悉了最基本的SpringBoot单元测试,接下来的章节会展开更多知识点和细节,对单元测试做更深入的学习

欢迎关注我的公众号:程序员欣宸

相关推荐

使用Python编写Ping监测程序(python 测验)

Ping是一种常用的网络诊断工具,它可以测试两台计算机之间的连通性;如果您需要监测某个IP地址的连通情况,可以使用Python编写一个Ping监测程序;本文将介绍如何使用Python编写Ping监测程...

批量ping!有了这个小工具,python再也香不了一点

号主:老杨丨11年资深网络工程师,更多网工提升干货,请关注公众号:网络工程师俱乐部下午好,我的网工朋友。在咱们网工的日常工作中,经常需要检测多个IP地址的连通性。不知道你是否也有这样的经历:对着电脑屏...

python之ping主机(python获取ping结果)

#coding=utf-8frompythonpingimportpingforiinrange(100,255):ip='192.168.1.'+...

网站安全提速秘籍!Nginx配置HTTPS+反向代理实战指南

太好了,你直接问到重点场景了:Nginx+HTTPS+反向代理,这个组合是现代Web架构中最常见的一种部署方式。咱们就从理论原理→实操配置→常见问题排查→高级玩法一层层剖开说,...

Vue开发中使用iframe(vue 使用iframe)

内容:iframe全屏显示...

Vue3项目实践-第五篇(改造登录页-Axios模拟请求数据)

本文将介绍以下内容:项目中的public目录和访问静态资源文件的方法使用json文件代替http模拟请求使用Axios直接访问json文件改造登录页,配合Axios进行登录请求,并...

Vue基础四——Vue-router配置子路由

我们上节课初步了解Vue-router的初步知识,也学会了基本的跳转,那我们这节课学习一下子菜单的路由方式,也叫子路由。子路由的情况一般用在一个页面有他的基础模版,然后它下面的页面都隶属于这个模版,只...

Vue3.0权限管理实现流程【实践】(vue权限管理系统教程)

作者:lxcan转发链接:https://segmentfault.com/a/1190000022431839一、整体思路...

swiper在vue中正确的使用方法(vue中如何使用swiper)

swiper是网页中非常强大的一款轮播插件,说是轮播插件都不恰当,因为它能做的事情太多了,swiper在vue下也是能用的,需要依赖专门的vue-swiper插件,因为vue是没有操作dom的逻辑的,...

Vue怎么实现权限管理?控制到按钮级别的权限怎么做?

在Vue项目中实现权限管理,尤其是控制到按钮级别的权限控制,通常包括以下几个方面:一、权限管理的层级划分...

【Vue3】保姆级毫无废话的进阶到实战教程 - 01

作为一个React、Vue双修选手,在Vue3逐渐稳定下来之后,是时候摸摸Vue3了。Vue3的变化不可谓不大,所以,本系列主要通过对Vue3中的一些BigChanges做...

Vue3开发极简入门(13):编程式导航路由

前面几节文章,写的都是配置路由。但是在实际项目中,下面这种路由导航的写法才是最常用的:比如登录页面,服务端校验成功后,跳转至系统功能页面;通过浏览器输入URL直接进入系统功能页面后,读取本地存储的To...

vue路由同页面重定向(vue路由重定向到外部url)

在Vue中,可以使用路由的重定向功能来实现同页面的重定向。首先,在路由配置文件(通常是`router/index.js`)中,定义一个新的路由,用于重定向到同一个页面。例如,我们可以定义一个名为`Re...

那个 Vue 的路由,路由是干什么用的?

在Vue里,路由就像“页面导航的指挥官”,专门负责管理页面(组件)的切换和显示逻辑。简单来说,它能让单页应用(SPA)像多页应用一样实现“不同URL对应不同页面”的效果,但整个过程不会刷新网页。一、路...

Vue3项目投屏功能开发!(vue投票功能)

最近接了个大屏项目,产品想在不同的显示器上展示大屏项目不同的页面,做出来的效果图大概长这样...

取消回复欢迎 发表评论: