Java文件存在却找不到:JUnit测试路径问题求助
解决JUnit测试中文件路径找不到的问题
问题背景
项目结构如下:
filePathTesting ┣📦test ┃ ┣ 📜TestCard.java ┃ ┣ 📜TestCardGame.java ┃ ┗ 📜valid5PlayersPack.txt ┗📦src ┣ 📜App.java ┣ 📜Card.java ┗ 📜CardGame.java
src/CardGame.java中的isValidPackFile方法负责校验文件路径和内容,运行主程序时传入"test/valid5PlayersPack.txt"可正常执行,但JUnit测试时,无论使用valid5PlayersPack.txt、../test/valid5PlayersPack.txt还是test/valid5PlayersPack.txt,均提示文件不存在。打印当前工作目录为filePathTesting_dba1f5ce/.。
解决方案
1. 使用类加载器获取测试资源(推荐)
JUnit测试时,通过类加载器从测试类所在目录读取资源,避免依赖工作目录的不确定性。修改测试方法:
@Test public void testIsValidPackFileValidFile() throws IOException{ int numPlayers=5; // 从当前测试类所在目录加载资源 URL resourceUrl = TestCardGame.class.getResource("valid5PlayersPack.txt"); if (resourceUrl == null) { fail("Test resource file not found"); } String filePath = new File(resourceUrl.getFile()).getAbsolutePath(); assertTrue("Valid file not recognised as valid", CardGame.isValidPackFile(filePath, numPlayers)); }
原理:类加载器会自动定位到test目录(测试类所在的目录),直接读取目标文件,不受工作目录变化影响。
2. 直接使用项目根目录相对路径
既然当前工作目录是项目根目录filePathTesting_dba1f5ce/,直接使用从根目录到文件的相对路径即可:
@Test public void testIsValidPackFileValidFile() throws IOException{ int numPlayers=5; String filePath = "test/valid5PlayersPack.txt"; // 项目根 -> test -> 文件 assertTrue("Valid file not recognised as valid", CardGame.isValidPackFile(filePath, numPlayers)); }
注意:确保测试代码中filePath确实设置为这个值,之前的错误可能是路径拼写或层级错误导致。
3. 重构文件读取逻辑,支持类路径与文件系统双读取
修改CardGame.java的方法,让它同时支持从类路径和文件系统读取文件,提升方法的健壮性:
public static boolean isValidPackFile(String packLocation, int numPlayers) { // 优先尝试类路径读取 try (InputStream inputStream = CardGame.class.getClassLoader().getResourceAsStream(packLocation)) { if (inputStream != null) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { return validateFileContent(reader, numPlayers); } } // 类路径找不到,尝试文件系统路径 File file = new File(packLocation); if (!file.exists() || !file.isFile()) { System.out.println("ERROR: Pack file does not exist"); return false; } try (BufferedReader reader = new BufferedReader(new FileReader(file))) { return validateFileContent(reader, numPlayers); } } catch (IOException e) { System.out.println("ERROR: Could not read pack file"); return false; } } // 提取内容校验逻辑,复用代码 private static boolean validateFileContent(BufferedReader reader, int numPlayers) throws IOException { String line; int lineCount = 0; while ((line = reader.readLine()) != null) { try { int num = Integer.parseInt(line); if (num <= 0) { System.out.println("ERROR: Pack file contains a non-positive integer"); return false; } lineCount++; } catch (NumberFormatException e) { System.out.println("ERROR: Pack file contains a non-integer"); return false; } } if (lineCount == numPlayers * 8) { return true; } else { System.out.println("ERROR: There are not " + 8 * numPlayers + " cards in the pack file"); return false; } }
使用方式:
- 测试时直接传入
"valid5PlayersPack.txt"(类加载器会从test目录读取) - 主程序运行时传入
"test/valid5PlayersPack.txt"(文件系统路径)
内容的提问来源于stack exchange,提问作者Bahkbar
相关产品推荐
相关产品推荐

