How To Read A File from JUnit Test 📎
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