我在单元测试中读取文本文件,并将一些输入文本文件放在资源文件夹中。以下是目录结构。
- src -> com -> au -> myapp -> util -> MyFileReader
- test -> com -> au -> myapp -> util -> MyFileReaderTest
- test -> com -> au -> myapp -> resources-> input.txt
请注意,src 和 test 在同一层次结构中。
public class MyFileReaderTest
{
ClassLoader classLoader = getClass().getClassLoader();
@Test
public void testReadInputFile() throws Exception
{
String file = classLoader.getResource("test/com/au/myapp/resources/input.txt").getFile();
List<String> result = InputFileReader.getInstance().readFile(file);
assertEquals("Size of the list should be 2", 2, result.size());
}
}
Classloader.getResource()
返回 null。非常感谢您的帮助。
最佳答案
类加载器使用类路径来加载资源。您的类(class)很可能位于 com.au.myapp.util
包中。不在包 test.com.au.myapp.util
中。
目录结构与包结构相匹配。这意味着目录 src 和 test 都是源代码根目录。
由于您的文件位于源根目录下的 com/au/myapp/resources
目录中,因此其包为 com.au.myapp.resources
。
所以你需要
classLoader.getResource("com/au/fitbits/resources/input.txt");
这是一个资源,从类路径加载。它现在可能是一个文件,因为您处于开发模式,并且类是直接从文件系统加载的。但是一旦投入生产,它们将不再从文件系统加载,而是从 jar 文件加载。所以你不能使用文件IO来读取这个资源的内容。所以用
classLoader.getResourceAsStream("com/au/fitbits/resources/input.txt")
并从此流中读取。
关于java - 在 JUnit 测试中读取资源文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40710420/