SpringBoot整合junit

SpringBoot 整合 junit 特别简单,分为以下三步完成:

|---|--------------------------------|
| 1 | 在测试类上添加 @SpringBootTest 注解 |
| 2 | 使用 @Autowired 注入要测试的资源 |
| 3 | 定义测试方法进行测试 |

1.实验准备:

创建一个名为 springboot_junit_test 的 SpringBoot 工程,工程目录结构如下

在 com.example.service 下创建 BookService 接口,内容如下

java 复制代码
public interface BookService {
    public void save();
}

在 com.example.service.impl 包写创建一个 BookServiceImpl 类,使其实现 BookService 接口,内容如下

java 复制代码
@Service
public class BookServiceImpl implements BookService {
    @Override
    public void save() {
        System.out.println("service is running!");
    }
}

2.编写测试类

在 test/java 下创建 com.example 包,在该包下创建测试类,将 BookService 注入到该测试类中

java 复制代码
@SpringBootTest
class SpringbootJunitTestApplicationTests {

    @Autowired
    public BookService bookService;
    @Test
    void contextLoads() {
        bookService.save();
    }

}

注意:这里的引导类所在包必须是测试类所在包及其子包。

例如:

引导类所在包是 com.example

测试类所在包是 com.example

如果不满足这个要求的话,就需要在使用 @SpringBootTest 注解时,使用 classes 属性指定引导类的字节码对象。如

@SpringBootTest(classes = SpringbootJunitTestApplicationTests.class)

3.运行测试方法

整合成功!

相关推荐
duxingzhe03117 分钟前
我的一些书
java·数据库·tomcat·数据库开发·etl工程师
2603_965148119 分钟前
商品价格监控 API 接口:从原理到实战的完整指南
java·前端·数据库·python·生活
AllData公司负责人1 小时前
AllData搭建AI中台,集成开源项目LabelStudio/CubeStudio,建设数据标注平台/机器学习平台
数据库·人工智能·机器学习·labelstudio·cubestudio
2601_962071001 小时前
Kimi K3 vs DeepSeek V4-Pro实测对比:2026年同一入口十道题,耗时与token消耗差在哪
android·java·数据库
mengzhi啊1 小时前
把数据存入sql数据库。qt,c++。
数据库·sql·qt
苏渡苇1 小时前
Spring Insight:跨服务调用链路是怎么串起来的?
spring boot·后端·spring·系统监控·apm
ManageEngineITSM1 小时前
工单优先级怎么定?影响×紧急度矩阵的设计与落地方法
java·大数据·运维·前端·数据库·变更管理
科研online1 小时前
数据资源:中国10年旅游流动网络数据集
数据库
智商网输送线配件1 小时前
电子制造零散耗材补货实战:小批量混批采购平台怎么选才不停机?
大数据·服务器·前端·数据库·自动化
小冯不疯2 小时前
集成中心架构:PULL × PUSH × 集成转换的三大引擎
数据库·架构