详细分析SpringBootTest中的测试类(附Demo)

目录

  • 前言
  • 1. 基本知识
  • 2. Demo
  • 3. 实战
    • 3.1 项目测试
    • 3.2 功能测试

前言

书写测试类,一般只需要加入@Test即可,但是结合Springboot项目来整体测试对应需要怎么下手

详细的Java知识点推荐阅读:java框架 零基础从入门到精通的学习路线 附开源项目面经等(超全)

1. 基本知识

涉及测试类的基本注解分析如下:

一、@SpringBootTest:加载完整的Spring应用上下文
使用场景:需要测试整个Spring Boot应用时使用,确保所有的Bean都能被正确加载

@SpringBootTest
public class MyApplicationTests {// 测试方法
}

二、@RunWith(SpringRunner.class):指定测试运行器,这里使用SpringRunner来运行Spring Boot测试
使用场景:结合JUnit 4使用时指定测试运行器

@RunWith(SpringRunner.class)
public class MyApplicationTests {// 测试方法
}

三、@Autowired:自动注入Spring管理的Bean
使用场景:在测试类中需要注入服务、仓库等Bean时使用

@Autowired
private MyService myService;

四、@Slf4j:使用Lombok提供的日志记录功能
使用场景:需要在类中记录日志时使用

@Slf4j
public class MyApplicationTests {// 可以使用log.info(), log.debug()等记录日志
}

五、@Test:标记一个方法为测试方法
使用场景:任何需要进行单元测试的方法都应使用该注解

@Test
public void testMethod() {// 测试逻辑
}

常出现的情况有如下:

  1. 注入的Bean为null
    使用@Autowired注入的Bean为null
    》》》》确保被注入的类被Spring管理(例如,使用@Service、@Component等注解),确保测试类使用@SpringBootTest注解以加载完整的Spring上下文

  2. 测试类无法加载上下文
    测试类无法加载Spring上下文,抛出BeanCreationException等异常
    》》》》确保@SpringBootTest注解的classes属性指向正确的主应用程序类,例如AccidentApplication.class

2. Demo

结合实战中的Demo进行讲解

import com.sinosoft.springbootplus.AccidentApplication;
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.test.context.junit4.SpringRunner;@SpringBootTest(classes = AccidentApplication.class)
@Slf4j
public class TestClass {@Autowiredprivate XXXService xxxService;@Testpublic void testDemo() {// 示例测试代码log.info("Starting testDemo");// 调用XXXService的某个方法,并进行断言String result = xxxService.someMethod();assertNotNull(result);log.info("testDemo completed");}
}

其中的注意事项如下:

  1. 类路径:确保AccidentApplication类在你的类路径下,并且可以被正确加载
  2. Service注入:XXXService必须在Spring上下文中被定义为一个Bean,否则@Autowired注入会失败
  3. JUnit版本:确保项目使用JUnit 5(JUnit Jupiter)或者JUnit 4,不要混用
    上面的代码中使用的是JUnit 5,如果你需要使用JUnit 4,请使用org.junit.Test和org.junit.runner.RunWith
  4. 日志使用:通过@Slf4j注解,可以在测试方法中方便地记录日志,这有助于调试

而且基本的项目结构如下:

src
├── main
│   └── java
│       └── com
│           └── manong
│               └── springbootplus
│                   ├── AccidentApplication.java
│                   └── service
│                       └── XXXService.java
└── test└── java└── com└── manong└── springbootplus└── TestClass.java

3. 实战

3.1 项目测试

Demo与实战中大同小异,上述使用的是JUnit 5 ,下面使用一个JUnit 4进行演示

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = YudaoServerApplication.class)
public class projectTest {@Testpublic void testUsingTosDataSource() {}}

实际截图如下:

在这里插入图片描述

3.2 功能测试

实战中可能有多个模块,对应的配置需如下:

package cn.example.module.dangerous.service.enterpriseregistry;import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.mock.mockito.MockBean;import javax.annotation.Resource;import cn.example.framework.test.core.ut.BaseDbUnitTest;import cn.example.module.dangerous.controller.admin.enterpriseregistry.vo.*;
import cn.example.module.dangerous.dal.dataobject.enterpriseregistry.EnterpriseRegistryDO;
import cn.example.module.dangerous.dal.mysql.enterpriseregistry.EnterpriseRegistryMapper;
import cn.example.framework.common.pojo.PageResult;import javax.annotation.Resource;
import org.springframework.context.annotation.Import;
import java.util.*;
import java.time.LocalDateTime;import static cn.hutool.core.util.RandomUtil.*;
import static cn.example.module.dangerous.enums.ErrorCodeConstants.*;
import static cn.example.framework.test.core.util.AssertUtils.*;
import static cn.example.framework.test.core.util.RandomUtils.*;
import static cn.example.framework.common.util.date.LocalDateTimeUtils.*;
import static cn.example.framework.common.util.object.ObjectUtils.*;
import static cn.example.framework.common.util.date.DateUtils.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;/*** {@link EnterpriseRegistryServiceImpl} 的单元测试类** @author 管理员*/
@Import(EnterpriseRegistryServiceImpl.class)
public class EnterpriseRegistryServiceImplTest extends BaseDbUnitTest {@Resourceprivate EnterpriseRegistryServiceImpl enterpriseRegistryService;@Resourceprivate EnterpriseRegistryMapper enterpriseRegistryMapper;@Testpublic void testCreateEnterpriseRegistry_success() {// 准备参数EnterpriseRegistrySaveReqVO createReqVO = randomPojo(EnterpriseRegistrySaveReqVO.class).setId(null);// 调用Long enterpriseRegistryId = enterpriseRegistryService.createEnterpriseRegistry(createReqVO);// 断言assertNotNull(enterpriseRegistryId);// 校验记录的属性是否正确EnterpriseRegistryDO enterpriseRegistry = enterpriseRegistryMapper.selectById(enterpriseRegistryId);assertPojoEquals(createReqVO, enterpriseRegistry, "id");}@Testpublic void testUpdateEnterpriseRegistry_success() {// mock 数据EnterpriseRegistryDO dbEnterpriseRegistry = randomPojo(EnterpriseRegistryDO.class);enterpriseRegistryMapper.insert(dbEnterpriseRegistry);// @Sql: 先插入出一条存在的数据// 准备参数EnterpriseRegistrySaveReqVO updateReqVO = randomPojo(EnterpriseRegistrySaveReqVO.class, o -> {o.setId(dbEnterpriseRegistry.getId()); // 设置更新的 ID});// 调用enterpriseRegistryService.updateEnterpriseRegistry(updateReqVO);// 校验是否更新正确EnterpriseRegistryDO enterpriseRegistry = enterpriseRegistryMapper.selectById(updateReqVO.getId()); // 获取最新的assertPojoEquals(updateReqVO, enterpriseRegistry);}@Testpublic void testUpdateEnterpriseRegistry_notExists() {// 准备参数EnterpriseRegistrySaveReqVO updateReqVO = randomPojo(EnterpriseRegistrySaveReqVO.class);// 调用, 并断言异常assertServiceException(() -> enterpriseRegistryService.updateEnterpriseRegistry(updateReqVO), ENTERPRISE_REGISTRY_NOT_EXISTS);}@Testpublic void testDeleteEnterpriseRegistry_success() {// mock 数据EnterpriseRegistryDO dbEnterpriseRegistry = randomPojo(EnterpriseRegistryDO.class);enterpriseRegistryMapper.insert(dbEnterpriseRegistry);// @Sql: 先插入出一条存在的数据// 准备参数Long id = dbEnterpriseRegistry.getId();// 调用enterpriseRegistryService.deleteEnterpriseRegistry(id);// 校验数据不存在了assertNull(enterpriseRegistryMapper.selectById(id));}@Testpublic void testDeleteEnterpriseRegistry_notExists() {// 准备参数Long id = randomLongId();// 调用, 并断言异常assertServiceException(() -> enterpriseRegistryService.deleteEnterpriseRegistry(id), ENTERPRISE_REGISTRY_NOT_EXISTS);}@Test@Disabled  // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解public void testGetEnterpriseRegistryPage() {// mock 数据EnterpriseRegistryDO dbEnterpriseRegistry = randomPojo(EnterpriseRegistryDO.class, o -> { // 等会查询到o.setEnterpriseName(null);o.setCreditCode(null);o.setRegistrant(null);o.setCreateTime(null);o.setEnterpriseCode(null);o.setContactNumber(null);});enterpriseRegistryMapper.insert(dbEnterpriseRegistry);// 测试 enterpriseName 不匹配enterpriseRegistryMapper.insert(cloneIgnoreId(dbEnterpriseRegistry, o -> o.setEnterpriseName(null)));// 测试 creditCode 不匹配enterpriseRegistryMapper.insert(cloneIgnoreId(dbEnterpriseRegistry, o -> o.setCreditCode(null)));// 测试 registrant 不匹配enterpriseRegistryMapper.insert(cloneIgnoreId(dbEnterpriseRegistry, o -> o.setRegistrant(null)));// 测试 createTime 不匹配enterpriseRegistryMapper.insert(cloneIgnoreId(dbEnterpriseRegistry, o -> o.setCreateTime(null)));// 测试 enterpriseCode 不匹配enterpriseRegistryMapper.insert(cloneIgnoreId(dbEnterpriseRegistry, o -> o.setEnterpriseCode(null)));// 测试 contactNumber 不匹配enterpriseRegistryMapper.insert(cloneIgnoreId(dbEnterpriseRegistry, o -> o.setContactNumber(null)));// 准备参数EnterpriseRegistryPageReqVO reqVO = new EnterpriseRegistryPageReqVO();reqVO.setEnterpriseName(null);reqVO.setCreditCode(null);reqVO.setRegistrant(null);reqVO.setCreateTime(buildBetweenTime(2023, 2, 1, 2023, 2, 28));reqVO.setEnterpriseCode(null);reqVO.setContactNumber(null);// 调用PageResult<EnterpriseRegistryDO> pageResult = enterpriseRegistryService.getEnterpriseRegistryPage(reqVO);// 断言assertEquals(1, pageResult.getTotal());assertEquals(1, pageResult.getList().size());assertPojoEquals(dbEnterpriseRegistry, pageResult.getList().get(0));}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/36748.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

vCenter-集群证书过期告警

VXR01405C ALARM Certificate is about to expire - 问题摘要&#xff1a;集群证书过期告警 - 分析/故障排除: 检查发现Machine SSL证书即将在7约25号过期。 - 解决方案/工作方法&#xff1a; 手动更新SSL证书并重启了vcenter服务后&#xff0c;目前machine SSL 证书续签到…

子组件与父组件数据的双向绑定

在Vue.js中&#xff0c;子组件与父组件之间的数据传递通常是单向的&#xff0c;即父组件向子组件传递数据&#xff08;通过props&#xff09;&#xff0c;而子组件向父组件发送消息&#xff08;通过事件&#xff09;。然而&#xff0c;如果你想要实现一种“双向绑定”的效果&am…

负载组类型:电阻式、无功型、电阻式电抗型、电子型

发电机通常用于紧急情况。就其本质而言&#xff0c;紧急情况经常意外发生&#xff0c;这就是为什么运营和设施&#xff0c;尤其是石油和天然气行业或服务行业&#xff08;例如数据中心和医院&#xff09;的运营和设施&#xff0c;在现场配备发电机以备不时之需。永久或便携式备…

idea中使用springboot进行开发时遇到的工程结构问题汇总

idea中的工程结构和eclipse中不同&#xff0c;但是配置的内容都是一样的。 IDEA中也就是这个页面&#xff0c;快捷键ctrlaltshifts 如果在eclipse中&#xff0c;经常会遇到jre和jdk不正确的情况&#xff0c;但IDEA中这个问题很少&#xff0c;但是IDEA中会经常由于未正常配置根…

使用Java进行RESTful API开发的最佳实践

使用Java进行RESTful API开发的最佳实践 大家好&#xff0c;我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编&#xff0c;也是冬天不穿秋裤&#xff0c;天冷也要风度的程序猿&#xff01;今天我们将探讨如何在Java中开发RESTful API的最佳实践。随着Web应用程…

[C#]基于opencvsharp实现15关键点人体姿态估计

数据集 正确选择数据集以对结果产生适当影响也是非常必要的。在此姿势检测中&#xff0c;模型在两个不同的数据集即COCO关键点数据集和MPII人类姿势数据集上进行了预训练。 1. COCO&#xff1a;COCO关键点数据集是一个多人2D姿势估计数据集&#xff0c;其中包含从Flickr收集的…

Java基础知识-线程同步和锁

1、实现线程同步有三种方式&#xff1f; 1. 同步代码块&#xff1a;在代码块上加上“synchronized”关键字的话&#xff0c;则此代码块就称为同步代 码块。 //同步代码块格式&#xff1a; synchronized(监视对象){ //需要同步的代码 ; } 解释&#xff1a;监视对象有三种&#…

【TensorFlow深度学习】自动回归模型在自我监督视觉特征学习中的应用

自动回归模型在自我监督视觉特征学习中的应用 在深度学习的探索之路上,自动回归模型凭借其独特的序列生成能力,在自我监督学习领域,尤其是在视觉特征学习方面,展现出了非凡的应用潜力。本文将深入剖析自动回归模型如何在计算机视觉中发挥作用,通过实例分析、理论探讨和未来…

#### grpc比http性能高的原因 ####

grpc比http性能高的原因 二进制消息格式&#xff1a;gRPC使用Protobuf&#xff08;一种有效的二进制消息格式&#xff09;进行序列化&#xff0c;这种格式在服务器和客户端上的序列化速度非常快&#xff0c;且序列化后的消息体积小&#xff0c;适合带宽有限的场景。 HTTP/2协…

海思SS928/SD3403开发笔记4——u盘挂载

首先一定要将u盘格式化成fat32。 挂载 mkdir /mnt/usb mount /dev/sda1 /mnt/usb成功示意图&#xff1a; 取消挂载 umount /mnt/usb

lighttpd安装和配置https

apt install lighttpd apt-get install php-cgi lighttpd-enable-mod fastcgi fastcgi-php service lighttpd force-reload lighttpd配置https sudo nano /etc/lighttpd/lighttpd.conf加入&#xff1a; server.modules ("mod_openssl") $SERVER["socket&quo…

59、Flink 的异步 IO 算子使用线程池查询 MySQL

1、概述 -----------Test1----------- 非静态 dataSource 和 executorService【一个并行度&#xff08;Task 线程&#xff09;一个实例】 分区1 dataSource>915342614 executorService>2120731873 分区2 dataSource>1271767714 executorService>844411403 并行度2…

数智化赋能水务行业高质量发展

数智化赋能水务行业高质量发展是指通过数字化和智能化技术的应用&#xff0c;提升水务行业的管理效率、服务质量和运营安全&#xff0c;实现可持续发展。以下是数智化赋能水务行业高质量发展的几个关键方面&#xff1a; 1. 智能水务管理平台 集成数据中心&#xff1a;建立统一…

C#——命名空间详情

命名空间 在 C# 中&#xff0c;可以将命名空间看作是一个范围&#xff0c;用来标注命名空间中成员的归属&#xff0c;一个命名空间中类与另一个命名空间中同名的类互不冲突&#xff0c;但在同一个命名空间中类的名称必须是唯一的。 定义命名空间 定义命名空间需要使用 namesp…

JS在线加密简述

JS在线加密&#xff0c;是指&#xff1a;在线进行JS代码混淆加密。通过混淆、压缩、加密等手段&#xff0c;使得JS源代码难以阅读和理解。从而可以有效防止代码被盗用或抄袭&#xff0c;保护开发者的知识产权和劳动成果。常用的JS在线加密网站有&#xff1a;JShaman、JS-Obfusc…

怎么在vite项目中全局导入一个scss文件

怎么在vite项目中全局导入一个scss文件 &#x1f389;&#x1f389;&#x1f389;欢迎来到我的博客,我是一名自学了2年半前端的大一学生,熟悉的技术是JavaScript与Vue.目前正在往全栈方向前进, 如果我的博客给您带来了帮助欢迎您关注我,我将会持续不断的更新文章!!!&#x1f64…

如何快速找到CAN总线的故障节点?

如何快速找到CAN总线的故障节点&#xff1f; 1、节点&#xff08;数量不多的情况&#xff09;依次接入总线&#xff1a;将CAN节点一个一个往总线上接&#xff0c;每接一个节点后观察、测试总线通信状况。2、使用CAN转换器或接口类产品辅助排查。&#xff08;快速定位&#xff…

【Redis】Java操作Redis(Jedis客户端使用)

Redis不仅支持简单的键值存储&#xff0c;还提供了丰富的数据结构&#xff08;如列表、哈希表、集合等&#xff09;和强大的原子操作&#xff0c;使得它在存储和处理数据时非常高效。关于这些数据结构的学习可以学习下面的博客&#xff1a; 【Redis】String的常用命令及图解St…

OBD诊断(ISO15031) 01服务

文章目录 功能简介PID 的功能请求和响应1、read-supported PIDs1.1、请求1.2、肯定响应 2、read PID value1.1、请求1.2、肯定响应 3、同时请求多个PID3、同时读取多个PID数据 Parameter definition报文示例1、单个PID请求和读取2、多个PID请求和读取 功能简介 01服务&#xf…

XML 技术

XML 技术 XML(可扩展标记语言)是一种用于存储和传输数据的标记语言。它由万维网联盟(W3C)开发,并在1998年成为正式标准。XML的设计目标是既易于人类阅读,也易于机器解析。它是一种自描述的语言,允许用户定义自己的标签和文档结构。XML被广泛应用于各种领域,包括网络服…