在将其标记为重复之前,请先阅读问题!
我有一个 JUnit 测试,它测试将其结果写入文件
的方法。为了检查结果,我想读取该结果文件并检查其内容。
问题在于,当测试开始之前结果文件尚不存在时,方法 getResourceAsStream()
返回 null
。
我的测试代码是这样的:
@Inject
private ObjectToTest obj
@Test
public void testMethod() throws Exception {
// Do some setup (inject mocks, set properties of obj, ...)
obj.method(); // <-- Creates result.txt
Mockito.verify(obj).method();
// Thread.sleep(1000); <-- I have tried to use this to wait some time for the result, but it did not work
// This part is null on the first run of the test
// When I run the test the second time, the file does already exist and it returns the right InputStream for the File
InputStream resultInp = this.getClass().getResourceAsStream("/test-out/result.txt");
String resultStr = IOUtils.toString(resultInp, "UTF-8");
assertThat(resultStr).isNotNull();
assertThat(resultStr.split("\n")).hasSize(5);
}
是否有任何解释为什么会发生这种情况,或者它必须对代码的另一部分执行某些操作?
我在 StackOverflow 上没有找到任何有关此问题的信息,但如果我错了,请引导我找到正确的帖子。
最佳答案
getResourceAsStream()
方法使用类加载器缓存的目录/索引信息返回类路径上资源的流。如果在缓存类路径后将资源添加到类路径上的某个目录树或存档,则类加载器可能不会“看到”它1。
这很可能是您的测试代码中发生的情况。
Java 应用程序不应尝试将类加载器资源视为通用文件系统。相反,使用 File
或 Path
来表示文件,并使用 FileInputStream
或类似的方法来打开它们。
1 - javadoc 中似乎没有为 ClassLoader
等指定实际行为。我的描述基于一些 Java 实现的观察/报告行为。
关于java - 当测试方法开始之前文件不存在时,为什么 getResourceAsStream() 返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56423302/