How to read a text-file resource into Java unit test?

Viewed 347957

I have a unit test that needs to work with XML file located in src/test/resources/abc.xml. What is the easiest way just to get the content of the file into String?

10 Answers

OK, for JAVA 8, after a lot of debugging I found that there's a difference between

URL tenantPathURI = getClass().getResource("/test_directory/test_file.zip");

and

URL tenantPathURI = getClass().getResource("test_directory/test_file.zip");

Yes, the / at the beginning of the path without it I was getting null!

and the test_directory is under the test directory.

Using Commons.IO, this method works from EITHER a instance method or a static method:

public static String loadTestFile(String fileName) {
    File file = FileUtils.getFile("src", "test", "resources", fileName);
    try {
        return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
    } catch (IOException e) {
        log.error("Error loading test file: " + fileName, e);
        return StringUtils.EMPTY;
    }
}
Related