简体   繁体   English

如果在Test方法启动之前文件不存在,为什么getResourceAsStream()返回null?

[英]Why does getResourceAsStream() return null when File does not exist before start of Test method?

Before flagging this as a duplicate please read the question! 在将其标记为重复项之前,请阅读问题!

I have a JUnit Test which tests a method that writes its result in a file . 我有一个JUnit Test,它测试一种将结果写入file To check the result I want to read that result file and check its content. 要检查结果,我想读取该结果文件并检查其内容。

The problem is that when the result file does not already exist before the start of the test, the method getResourceAsStream() returns null . 问题是,当测试开始之前结果文件尚不存在时,方法getResourceAsStream()返回null

My code for the Test is something like this: 我的测试代码是这样的:

@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);
}

Is there any explanation to why this happens or must it have to do something with another part of the code? 是否有任何解释说明为什么会发生这种情况,还是必须对代码的另一部分进行某些处理?

I have not found anything regarding this issue on StackOverflow, but if I am wrong please guide me to the right post. 我没有在StackOverflow上找到与此问题有关的任何内容,但是如果我错了,请引导我转到正确的位置。

The getResourceAsStream() method returns a stream for a resource on the classpath, using directory / index information that is cached by the classloader. getResourceAsStream()方法使用由类加载器缓存的目录/索引信息返回类路径上资源的流。 If you add a resource to some directory tree or archive on the classpath after the classpath has been cached, the classloader is likely to not "see" it 1 . 如果在将类路径缓存后将资源添加到类路径的某个目录树或归档中,则类加载器可能不会“看到”它1

That is most likely is what has happened in your test code. 这很可能是测试代码中发生的事情。

A Java application should not be trying to treat classloader resources like a general purpose file system. Java应用程序不应试图将类加载器资源视为通用文件系统。 Instead, use File or Path to denote files, and FileInputStream or similar to open them. 而是使用FilePath表示文件,并使用FileInputStream或类似文件打开它们。


1 - The actual behavior does not appear to be specified in the javadocs for ClassLoader , etcetera. 1-在javadocs中, ClassLoader等未指定实际行为。 My description is based on the observed / reported behavior of some Java implementations. 我的描述基于某些Java实现的观察/报告行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM