1. 概述

在单元测试过程中,我们常常需要从 classpath 读取文件、向测试对象传入文件,或者使用存放在 src/test/resources 中的测试数据(比如用于 WireMock 的 stub 数据)。

本文将介绍 如何在 JUnit 中获取项目的 /src/test/resources 目录路径。我们会分别使用 FilePathClassLoader 这三种方式来实现,并分析它们之间的差异。

2. Maven 依赖

要运行 JUnit 5 测试,我们首先需要引入 JUnit 的依赖:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.10.2</version>
</dependency>

你可以在 Maven Central 上查看最新版本。

3. 使用 java.io.File

这是最简单粗暴的方式。我们通过创建 File 实例,直接读取 src/test/resources 路径并获取绝对路径:

String path = "src/test/resources";

File file = new File(path);
String absolutePath = file.getAbsolutePath();

System.out.println(absolutePath);

assertTrue(absolutePath.endsWith("src/test/resources"));

输出示例(macOS):

/Users/user.name/my_projects/tutorials/testing-modules/junit-5-configuration/src/test/resources

✅ 优点:简单直观
❌ 缺点:路径是相对于项目根目录的,若项目结构变化容易踩坑

4. 使用 Path(Java 7+)

从 Java 7 开始,我们可以使用 java.nio.file.Path,更现代也更灵活:

Path resourceDirectory = Paths.get("src", "test", "resources");
String absolutePath = resourceDirectory.toFile().getAbsolutePath();

System.out.println(absolutePath);

assertTrue(absolutePath.endsWith("src/test/resources"));

输出结果与上面一致:

/Users/user.name/my_projects/tutorials/testing-modules/junit-5-configuration/src/test/resources

✅ 优点:跨平台兼容性更好,路径拼接更清晰
⚠️ 注意:底层依然依赖当前工作目录,和 File 类似

5. 使用 ClassLoader

这是最常用于读取 classpath 资源的方式。适用于读取打包后的资源文件路径:

String resourceName = "example_resource.txt";

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(resourceName).getFile());
String absolutePath = file.getAbsolutePath();

System.out.println(absolutePath);

assertTrue(absolutePath.endsWith("/example_resource.txt"));

输出示例:

/Users/user.name/my_projects/tutorials/testing-modules/junit-5-configuration/target/test-classes/example_resource.txt

⚠️ 注意:这个路径指向的是 target/test-classes/,而不是 src/test/resources,因为 Maven 编译后资源会被复制到 target 下。

✅ 优点:适用于读取 classpath 中的资源文件
❌ 缺点:路径不是源码目录,不能直接访问 src/test/resources 原始路径

6. 总结

方法 适用场景 注意事项
File 简单读取项目目录结构 路径依赖当前工作目录
Path 更现代、跨平台的路径操作 File 类似
ClassLoader 读取 classpath 资源 实际路径是 target/test-classes

根据你的实际需求选择合适的方式。如果你只是想访问原始资源目录,推荐使用前两种方式;如果你需要访问打包后的资源,则用 ClassLoader 更合适。

完整示例代码可在 GitHub 项目 中查看。


原始标题:Get the Path of the /src/test/resources Directory in JUnit