在 JUnit 中获取 /src/test/resources 目录的路径
上次更新:2024 年 3 月 17 日
1. 概述
在单元测试期间,我们有时可能需要从类路径读取文件,或者将文件传递给被测对象。我们可能还在 src/test/resources 中有一个包含数据的文件,这些数据可被类似 WireMock 的库用作桩数据。
在本教程中,我们将学习如何读取 /src/test/resources 目录的路径。
2. Maven 依赖
首先,我们需要将 JUnit 5 添加到 Maven 依赖项
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.11.0-M2</version>
</dependency>
我们可以在 Maven Central 上找到 JUnit 5 的最新版本。
2. 使用 java.io.File
最简单的方法是使用 java.io.File 类的一个实例来读取 /src/test/resources 目录,方法是调用 getAbsolutePath() 方法
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
3. 使用 Path
接下来,我们可以使用 Java 7 中引入的 Path 类。
首先,我们需要调用一个静态工厂方法,Paths.get()。然后我们将 Path 转换为 File。最后,我们只需调用 getAbsolutePath(),就像在前面的示例中一样
Path resourceDirectory = Paths.get("src","test","resources");
String absolutePath = resourceDirectory.toFile().getAbsolutePath();
System.out.println(absolutePath);
Assert.assertTrue(absolutePath.endsWith("src/test/resources"));
并且我们得到与先前示例相同的输出
/Users/user.name/my_projects/tutorials/testing-modules/junit-5-configuration/src/test/resources
4. 使用 ClassLoader
最后,我们也可以使用 ClassLoader
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
请注意,这次我们有一个 /junit-5-configuration/target/test-classes/example-resource.txt 文件。它与我们与先前方法比较的结果不同。
这是因为 ClassLoader 在类路径上查找资源。在 Maven 中,编译后的类和资源被放置在 /target/ 目录中。这就是为什么这次我们获得了指向类路径资源的路径。
5. 结论
在这篇简短的文章中,我们讨论了如何在 JUnit 5 中读取 /src/test/resources 目录。
根据我们的需求,我们可以使用多种方法实现我们的目标:File、Paths 或 ClassLoader 类。
支持本文的代码可在 GitHub 上获取。 一旦你以 Baeldung Pro 会员 身份登录,就开始学习并在项目上进行编码。















