Junit + getResourceAsStream Returning Null

后端 未结 13 1350
情话喂你
情话喂你 2020-12-15 03:32

Not sure how this is possible. I re-read up on getResourceAsStream and it\'s always returning null.

InputStream source = this.getClass().getResourceAsStream(         


        
相关标签:
13条回答
  • 2020-12-15 03:39

    I spent lot of time in this problem and it was missing me the following configuration: Right-click on an eclipse project and select Properties -> Java Build Path -> Source and edit Included row and add *.properties (*.fileExtension)

    0 讨论(0)
  • 2020-12-15 03:40

    getResourceAsStream() is using the CLASSPATH, and as such it will load from wherever your classes are, not your source files.

    I suspect you need to copy your XML to the same directory as your .class file.

    0 讨论(0)
  • 2020-12-15 03:40

    Put test.xml in the src/main/resources (or src/test/resources).

    File file = ResourceUtils.getFile("classpath:test.xml");
    String test = new String(Files.readAllBytes(file.toPath()));
    
    0 讨论(0)
  • 2020-12-15 03:41

    You need to put the copy of your resource file to the test resources, in my example it is font file:

    Then call next from your jUnit test:

     public static InputStream getFontAsStream() throws IOException {
            return Thread.currentThread().getContextClassLoader()
                        .getResourceAsStream("fonts/" + "FreeSans.ttf");
        }
    
    0 讨论(0)
  • 2020-12-15 03:46

    I had this problem with a Spring class. System.class.getResourceAsStream(...) worked in unit tests but not in Tomcat, Thread.currentThread().getContextClassLoader().getResourceAsStream(...) worked in Tomcat but not in unit tests.

    Ulitimately I went with:

    ClassUtils.getDefaultClassLoader()
        .getResourceAsStream("com/example/mail/templates/invoice-past-due.html"))
    

    I also found that once I did it this way, I did not need to have the path starting with a slash.

    0 讨论(0)
  • 2020-12-15 03:52

    From Java API:

    http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getSystemResource(java.lang.String)

    Find a resource of the specified name from the search path used to load classes. This method locates the resource through the system class loader

    So the syntax will for instance be: ClassLoader.getSystemResource("test.xml").toString();

    Works like a charm!

    0 讨论(0)
提交回复
热议问题