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

相关推荐
xuzhiqiang072419 小时前
Java进阶之路,Java程序员职业发展规划
java·开发语言
时艰.20 小时前
订单系统历史数据归档方案
java
一只叫煤球的猫21 小时前
ThreadForge v1.1.0 发布:让 Java 并发更接近 Go 的开发体验
java·后端·性能优化
014.1 天前
2025最新jenkins保姆级教程!!!
java·运维·spring boot·spring·jenkins
浣熊8881 天前
天机学堂虚拟机静态ip无法使用(重启后ip:192.168.150.101无法使用连接Mobaxterm数据库等等,或者无法使用修改之后的Hosts域名去访问nacos,jenkins)
java·微服务·虚拟机·天机学堂·重启之后静态ip用不了
心 -1 天前
java八股文IOC
java
I_LPL1 天前
day34 代码随想录算法训练营 动态规划专题2
java·算法·动态规划·hot100·求职面试
亓才孓1 天前
【MyBatis Exception】Public Key Retrieval is not allowed
java·数据库·spring boot·mybatis
J_liaty1 天前
Java设计模式全解析:23种模式的理论与实践指南
java·设计模式
Desirediscipline1 天前
cerr << 是C++中用于输出错误信息的标准用法
java·前端·c++·算法