How To Read A File from JUnit Test

To read the file: src/test/resources/test.file in a unit/integration test, the method Path.of is useful to set the working directory:


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Before;
import org.junit.Test;    

public class ReadFileTest {

    private Path workingDir;

    @Before
    public void init() {
        this.workingDir = Path.of("", "src/test/resources");
    }

    @Test
    public void read() throws IOException {
        Path file = this.workingDir.resolve("test.file");
        String content = Files.readString(file);
        assertThat(content, is("duke"));
    }

}    

The method Files.readString ships with Java 11+.

Path.of should be preferred over Paths.get. Thanks to @sormuras for the hint

Comments:

Too many lines of code for such a simple thing.

Posted by Simplifier on April 14, 2020 at 09:18 PM CEST #

"It is recommended to obtain a Path via the Path.of methods instead of via the get methods defined in this class as this class may be deprecated in a future release."

From https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Paths.html

Posted by Christian Stein on April 15, 2020 at 09:45 AM CEST #

An option without hardcoding src/test/resources:

try (InputStream inputStream = ReadResourceTest.class.getResourceAsStream("test.file")) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
inputStream.transferTo(bos);
String content = bos.toString(UTF_8);
assertThat(content, is("duke"));
}

With help from here:
https://stackoverflow.com/questions/309424/how-do-i-read-convert-an-inputstream-into-a-string-in-java/35066091#35066091

Posted by Arend v. Reinersdorff on April 18, 2020 at 03:49 PM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License