如何为基于DirectoryStream的目录遍历方法编写JUnit测试并解决路径报错
问题与解决方法
现有业务代码
你在Test.java类中编写了通过try-with-resources机制管理DirectoryStream资源的方法,遍历传入路径下的所有条目,筛选出所有子目录并封装为List<Path>类型返回:
public List<Path> getAllFoldersInTmp(String directory) throws IOException { final List<Path> files = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(Path.of(directory))) { for (Path entry : stream) { if (Files.isDirectory(entry)) { files.add(entry); } } } return files; }
该方法原本设计用途是返回../../tmp路径下的全部子文件夹。
测试报错场景
你为上述方法编写了单元测试,运行时始终无法正常工作,抛出如下异常:
..\..\Temp java.nio.file.NoSuchFileException: ..\..\Temp
对应的测试代码如下:
import java.io.File; import java.io.IOException; import java.nio.file.Path; import org.junit.jupiter.api.Test; class Testing{ @Autowired Test test; @TempDir Path directory; @Test public void givenDir_whenUsingDirectoryStream_thenListAllFiles() throws IOException { File fileOne = directory.resolve("file1").toFile(); File fileTwo = directory.resolve("file2").toFile(); System.out.println(test.getAllFoldersInTmp("../../Temp")); // 你以为file1、file2会存储在Temp/随机数目录下 } }
问题根因
- 路径硬编码错误:JUnit 5的
@TempDir会在系统临时目录下生成随机命名的独立测试目录,和你手写的../../Temp相对路径没有任何映射关系。这个相对路径是相对于测试进程的启动工作目录解析的,目标路径根本不存在,自然触发找不到文件的异常。- 测试实体未创建:代码里通过
resolve().toFile()只生成了JVM内存中的File对象,没有真正在磁盘上创建对应的文件/目录实体,就算路径正确,遍历也拿不到预期内容。
正确的测试写法
- 不要硬编码相对路径,直接将
@TempDir生成的绝对路径转成字符串传入方法即可,完全不需要手动拼接../../Temp这类相对路径。 - 测试过程中先通过
Files工具类在临时目录下创建需要的子目录、测试文件实体,再执行遍历方法做断言。 - 因为代码用了
@Autowired注入测试类,需要保证测试类添加了对应的Spring测试启动注解,否则注入的Test对象为null会触发空指针。
可直接运行的修改后测试代码:
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class Testing{ @Autowired Test test; @TempDir Path directory; @Test public void givenDir_whenUsingDirectoryStream_thenListAllFiles() throws IOException { // 在临时目录下创建测试实体:2个子目录、1个普通文件 Files.createDirectory(directory.resolve("subFolder1")); Files.createDirectory(directory.resolve("subFolder2")); Files.createFile(directory.resolve("normalFile.txt")); // 传入临时目录的绝对路径执行方法 List<Path> result = test.getAllFoldersInTmp(directory.toString()); // 断言返回的子目录数量符合预期 assert result.size() == 2; } }
内容的提问来源于stack exchange,提问作者Catalina
相关产品推荐
相关产品推荐

