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

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

ztj100 2025-01-14 19:11 56 浏览 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单元测试,接下来的章节会展开更多知识点和细节,对单元测试做更深入的学习

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

相关推荐

其实TensorFlow真的很水无非就这30篇熬夜练

好的!以下是TensorFlow需要掌握的核心内容,用列表形式呈现,简洁清晰(含表情符号,<300字):1.基础概念与环境TensorFlow架构(计算图、会话->EagerE...

交叉验证和超参数调整:如何优化你的机器学习模型

准确预测Fitbit的睡眠得分在本文的前两部分中,我获取了Fitbit的睡眠数据并对其进行预处理,将这些数据分为训练集、验证集和测试集,除此之外,我还训练了三种不同的机器学习模型并比较了它们的性能。在...

机器学习交叉验证全指南:原理、类型与实战技巧

机器学习模型常常需要大量数据,但它们如何与实时新数据协同工作也同样关键。交叉验证是一种通过将数据集分成若干部分、在部分数据上训练模型、在其余数据上测试模型的方法,用来检验模型的表现。这有助于发现过拟合...

深度学习中的类别激活热图可视化

作者:ValentinaAlto编译:ronghuaiyang导读使用Keras实现图像分类中的激活热图的可视化,帮助更有针对性...

超强,必会的机器学习评估指标

大侠幸会,在下全网同名[算法金]0基础转AI上岸,多个算法赛Top[日更万日,让更多人享受智能乐趣]构建机器学习模型的关键步骤是检查其性能,这是通过使用验证指标来完成的。选择正确的验证指...

机器学习入门教程-第六课:监督学习与非监督学习

1.回顾与引入上节课我们谈到了机器学习的一些实战技巧,比如如何处理数据、选择模型以及调整参数。今天,我们将更深入地探讨机器学习的两大类:监督学习和非监督学习。2.监督学习监督学习就像是有老师的教学...

Python教程(三十八):机器学习基础

...

Python 模型部署不用愁!容器化实战,5 分钟搞定环境配置

你是不是也遇到过这种糟心事:花了好几天训练出的Python模型,在自己电脑上跑得顺顺当当,一放到服务器就各种报错。要么是Python版本不对,要么是依赖库冲突,折腾半天还是用不了。别再喊“我...

超全面讲透一个算法模型,高斯核!!

...

神经网络与传统统计方法的简单对比

传统的统计方法如...

AI 基础知识从0.1到0.2——用“房价预测”入门机器学习全流程

...

自回归滞后模型进行多变量时间序列预测

下图显示了关于不同类型葡萄酒销量的月度多元时间序列。每种葡萄酒类型都是时间序列中的一个变量。假设要预测其中一个变量。比如,sparklingwine。如何建立一个模型来进行预测呢?一种常见的方...

苹果AI策略:慢哲学——科技行业的“长期主义”试金石

苹果AI策略的深度原创分析,结合技术伦理、商业逻辑与行业博弈,揭示其“慢哲学”背后的战略智慧:一、反常之举:AI狂潮中的“逆行者”当科技巨头深陷AI军备竞赛,苹果的克制显得格格不入:功能延期:App...

时间序列预测全攻略,6大模型代码实操

如果你对数据分析感兴趣,希望学习更多的方法论,希望听听经验分享,欢迎移步宝藏公众号...

AI 基础知识从 0.4 到 0.5—— 计算机视觉之光 CNN

...

取消回复欢迎 发表评论: