【Spring】Spring 整合 JUnit

JUnit 是 Java 中一个广泛使用的单元测试框架。它使用简单的注解和断言方法,使开发者能够轻松编写和运行测试用例。在使用 IDEA 创建的 Spring 项目中,JUnit 框架可以方便地进行整合。下面是整合的具体步骤。这里使用一个之前整合 MyBatis 时的 Spring 项目。关于如何从零开始整合 MyBatis 的详细过程,可以参考这篇文章:《Spring 整合 MyBatis》。

(1)导入依赖

在 Spring 项目的 pom.xml 文件中导入 junit 依赖和 Spring 整合 junit 依赖:

xml 复制代码
<!-- junit 依赖 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>3.8.1</version>
    <scope>test</scope>
</dependency>

<!-- Spring Test 依赖 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.10.RELEASE</version>
</dependency>

(2)创建测试接口

以测试业务层接口为例,在 src/test/java 下的 service 目录中创建一个测试类。确保 service 的路径与 src/main/java 中的结构一致,例如,如果 groupId 为 com.it,则完整路径应为 src/test/java/com/it/service:

java 复制代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {
    @Autowired
    private UserService userService;

    @Test
    public void testFindById() {
        User user = userService.findById(1);
        System.out.println(user);
    }
}

其中,@RunWith 注解指定了 Spring 整合 JUnit 的专用类运行器,@ContextConfiguration 注解指定了 Spring 框架的核心配置类,@Test 注解指定了 testFindById 方法为测试方法。

(3)运行测试方法

IDEA 会在测试方法旁边显示运行按钮,点击即可运行测试结果:

相关推荐
高频因子挖掘机2 分钟前
别急着搭数据平台:量化策略开发如何用最小闭环验证想法
后端·github·api
叶总没有会12 分钟前
RabbitMQ基础--java客户端
java·rabbitmq·java-rabbitmq
CCblandy21 分钟前
一致性哈希到底省了多少搬迁?本机实测 3 轮:取模 6→7 搬 85.8%,V=128 只搬 14.3%,虚拟节点太少会被倾斜骗
后端·python·云原生·性能优化·架构
小陈不好吃34 分钟前
Java 泛型与类型擦除:从 PECS 原则到 TypeToken 绕过
java·开发语言·windows·pecs 原则·typetoken绕过
鶴哥只手遮天39 分钟前
Spring Framework 7.0.9 深度剖析-03-IoC 容器核心:BeanFactory 与 BeanDefinition 体系
java·后端·开源
tianbin91142 分钟前
大模型流式输出异常排查,API 中转站层面的问题定位思路
后端·云计算
ydjs678899-bot1 小时前
如何在Java中打印pdf静默打印和打印对话框选择
java·python·pdf
Shaoshing1 小时前
存储引擎与架构
java·开发语言·架构
鶴哥只手遮天1 小时前
Spring Framework 7.0.9 深度剖析-01-整体架构与设计哲学
java·后端·开源
const_qiu1 小时前
第 2.5 章 2.5.6:前端登录、Token 无感续签与路由守卫
java·前端·人工智能·状态模式