How to get file resource from Maven src/test/resources/ folder in JUnit test?

Language/JAVA 2014. 11. 14. 11:31

Maven standard directory layout guide us to place any non-Java files for testing undersrc/test/resources/ folder. They are automatically copied over to target/test-classes/ folder during test phase.

Image you have the following folder layout:

src/
   main/
      java/
         SomeClass.java
   test/
      java/
         SomeClassTest.java
      resources/
         sample.txt

The question is how to reach test file resource from JUnit test method.

Test file existence 

The basically you should test whether required test file resource does exists:

@Test
public void testStreamToString() {
   assertNotNull("Test file missing", 
               getClass().getResource("/sample.txt"));
   ...
}

Test file to stream 

Please note how getResource() argument value looks. Test class getResource() will resolve/sample.txt properly to /target/test-classes/sample.txt.

You might need to get InputStream from file resource which is easy to done with help of sister methodgetResourceAsStream():

// JDK7 try-with-resources ensures to close stream automatically
try (InputStream is = getClass().getResourceAsStream("/sample.txt")) {
        int Byte;       // Byte because byte is keyword!
        while ((Byte = is.read()) != -1 ) {
                System.out.print((char) Byte);
        }
}

Test file to File or Path 

Common is also to convert resource to java.io.File or its JDK7 successor java.nio.file.Path (from so-called NIO.2). I present Path example to print last modification time of test resource filesrc/test/resources/sample.txt:

URL resourceUrl = getClass().
getResource("/sample.txt");
Path resourcePath = Paths.get(resourceUrl.toURI());
FileTime lmt = Files.getLastModifiedTime(resourcePath);
// prints e.g. "Tue Jul 09 16:35:51 CEST 2013"
System.out.println(new Date(lmt.toMillis()));

출처 - http://devblog.virtage.com/2013/07/how-to-get-file-resource-from-maven-srctestresources-folder-in-junit-test/

'Language > JAVA' 카테고리의 다른 글

JAVA JSON 라이브러리 Jackson 사용법  (0) 2014.11.27
serialVersionUID 용도  (0) 2014.11.14
Class.getResource vs. ClassLoader.getResource  (0) 2014.11.14
[Apache Commons]Configuration  (0) 2014.11.11
pageContext 내장 객체  (0) 2014.11.11
: