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

整合成功!

相关推荐
itjinyin1 分钟前
SpringBoot + vue 管理系统
vue.js·spring boot·后端
曾阿伦9 分钟前
SQL 用法详解:从基础操作到进阶实战的全场景指南
数据库·sql
NCU_wander10 分钟前
操作系统/数据库和业务应用/中间件/硬件之间的关系
数据库·中间件
Navicat中国12 分钟前
如何从0到1完成函数设计 | Navicat 教程
数据库·函数·navicat
jnrjian16 分钟前
Oracle tablespace 对象迁移
数据库·oracle
chushiyunen17 分钟前
人工智能-function calling(函数调用)
数据库·ai编程
TDengine (老段)21 分钟前
TDengine IDMP 0-阅读指南
大数据·数据库·人工智能·时序数据库·tdengine·涛思数据
2501_9454248025 分钟前
机器学习与人工智能
jvm·数据库·python
Liu6288827 分钟前
Python单元测试(unittest)实战指南
jvm·数据库·python