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

整合成功!

相关推荐
行百里er7 小时前
WebSocket 在 Spring Boot 中的实战解析:实时通信的技术利器
spring boot·后端·websocket
皮皮林5517 小时前
SpringBoot 集成 Hera,让日志查看从 “找罪证” 变 “查答案”!
spring boot
2501_948195347 小时前
RN for OpenHarmony英雄联盟助手App实战:主导航实现
数据库
Filotimo_8 小时前
N+1查询问题
数据库·oracle
fenglllle9 小时前
spring-data-jpa saveall慢的原因
数据库·spring·hibernate
yangminlei9 小时前
Spring 事务探秘:核心机制与应用场景解析
java·spring boot
DarkAthena10 小时前
【GaussDB】执行索引跳扫时如果遇到该索引正在执行autovacuum,可能会导致数据查询不到
数据库·gaussdb
短剑重铸之日10 小时前
《7天学会Redis》Day 5 - Redis Cluster集群架构
数据库·redis·后端·缓存·架构·cluster
007php00710 小时前
mySQL里有2000w数据,Redis中只存20w的数据,如何保证Redis中的数据都是热点数据
数据库·redis·git·mysql·面试·职场和发展·php