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

+1 vote
6,892 views
asked Nov 20, 2020 by Hitesh Garg (799 points)  

Currently, I am testing a RestController in Java and using MockMVC to test the endpoint. Right now I am building the Object required by the method and then sending its json to the endpoint.

But by this method tests are getting lengthy and I want to extract this json out in a .json file in test resources something like src/test/resources/somefilename.json.

I am currently facing some difficulty on how to read the test file for a Junit test from test resources.

1 Answer

+1 vote
answered Nov 21, 2020 by Rahul Singh (682 points)  
selected Nov 21, 2020 by Hitesh Garg
 
Best answer

I generally prefer a very simple basic one without use of any libraries..

From Java 11 version

Since Java 11 there is a new method readString() to read small files as a String, preserving line terminators:

String content = Files.readString(path, StandardCharsets.US_ASCII);

Using getClass().getClassLoader(). getResourceAsStream(fileName)

private String slurpResources(String fileName) throws IOException {
  var classLoader = getClass().getClassLoader();
  return new String(classLoader.getResourceAsStream(fileName).readAllBytes());
}
commented May 24, 2021 by Tom Bezlar (10 points)  
Thank you!
Just happened to see this thread and your reply was helpful to me.
...