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.运行测试方法

整合成功!

相关推荐
阿成学长_Cain1 分钟前
Linux ipcs 命令超全详解:查看共享内存 / 消息队列 / 信号量,IPC 运维必备
linux·运维·服务器·网络·数据库
OceanBase数据库官方博客2 小时前
OceanBase AI 时代,数据库的变与不变(技术解析与实践)
数据库·人工智能·oceanbase
阿成学长_Cain4 小时前
Linux dirs命令详解|Bash目录堆栈管理快速切换目录实战教程
linux·运维·前端·数据库
ywl4708120874 小时前
Mysql 平衡二叉树、红黑树、B树、B+树区别以及应用场景(五)
数据库·b树·mysql
IvorySQL4 小时前
IvorySQL Agent 探索与实践
数据库·人工智能·postgresql·oracle·ivorysql
Listen·Rain5 小时前
提示词和提示词模板
java·人工智能·spring boot
SelectDB5 小时前
美团数十 PB 规模 Apache Doris 实践:从统一 OLAP 到 AI-Native 数据基座
大数据·数据库·性能优化
Database_Cool_5 小时前
阿里云RDS主从延迟解决方案_只读实例半同步复制最佳实践
数据库·人工智能
KaMeidebaby6 小时前
卡梅德生物技术快报|小 RNA 适配体合成 + 多方法亲和力表征全流程标准化操作手册
前端·网络·数据库·人工智能·算法
卓怡学长6 小时前
w269基于spring boot + vue 候鸟监测数据管理系统
java·数据库·spring boot·spring·intellij-idea