【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 会在测试方法旁边显示运行按钮,点击即可运行测试结果:

相关推荐
手握风云-1 分钟前
ProtoBuf:从序列化原理到高性能架构底座(一)
java·网络·架构
摇滚侠16 分钟前
SpringMVC 入门到实战 配置类替换 XML 配置文件 86-91
xml·java·后端·spring·maven·intellij-idea
栗子~~18 分钟前
金融场景下BigDecimal 运算规范 + 常用场景使用 + 数据库字段设计详解
java·数据库·金融
我登哥MVP22 分钟前
SpringCloud Alibaba 核心组件解析:服务注册与发现(Nacos)
java·spring boot·后端·spring·spring cloud·java-ee·maven
兰令水27 分钟前
leecodecode【单调栈】【2026.6.12打卡-java版本】
java·开发语言·算法
云烟成雨TD32 分钟前
Agent Scope Java 2.x 系列【8】工具调用
java·人工智能·agent
AI人工智能+电脑小能手40 分钟前
【大白话说Java面试题 第112题】【并发篇】第12题:AQS 中节点的入队时机有哪些?
java·开发语言·面试
摇滚侠41 分钟前
SpringMVC 入门到实战 处理静态资源的过程 64
java·后端·spring·maven·intellij-idea
影寂ldy41 分钟前
C# 泛型委托
java·算法·c#
摇滚侠43 分钟前
MyBatis 入门到项目实战 MyBatis 核心配置文件 15-19
java·tomcat·mybatis