Can somebody suggest an easy way to get a reference to a file as a String/InputStream/File/etc type object in a junit test class? Obviously I could paste the file (xml in t
If you want to load a test resource file as a string with just few lines of code and without any extra dependencies, this does the trick:
public String loadResourceAsString(String fileName) throws IOException {
Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(fileName));
String contents = scanner.useDelimiter("\\A").next();
scanner.close();
return contents;
}
"\\A" matches the start of input and there's only ever one. So this parses the entire file contents and returns it as a string. Best of all, it doesn't require any 3rd party libraries (like IOUTils).