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

整合成功!

相关推荐
Databend7 小时前
在 AWS 中国峰会逛了一天,我在 Databend 展台看到了 Agent 数据基础设施的新思路
数据库·人工智能·agent
ClouGence1 天前
Oracle 数据同步为什么会出现数据不一致?长事务是常被忽略的原因
数据库·后端·oracle
飞将2 天前
从零实现数据库(2)——HashIndex + IndexManager
数据库
java小白小2 天前
SpringBoot(01): 初识SpringBoot,从Spring的痛点说起
spring boot
Nturmoils2 天前
订单列表慢查询,先看 WHERE、ORDER BY 和 LIMIT
数据库
用户3169353811833 天前
如何从零编写一个 Spring Boot Starter
spring boot
渣波3 天前
拒绝 SQL 焦虑!手把手带你用 NestJS + Prisma + DTO 写出“防弹”级后端代码
javascript·数据库·后端
程序员晓琪3 天前
约定大于配置:基于 Java 包名自动生成 API 版本路由的最佳实践
java·spring boot·后端
Flittly3 天前
【AgentScope Java新手村系列】(11)中断与恢复
java·spring boot·spring
倔强的石头_4 天前
KingbaseES 新版MySQL 兼容版体验:旧版迁移 + 功能实测
数据库