Easy way to get a test file into JUnit

前端 未结 5 1792
面向向阳花
面向向阳花 2020-12-08 04:04

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

5条回答
  •  伪装坚强ぢ
    2020-12-08 04:29

    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).

提交回复
热议问题