Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot: How to read resource from classpath in unit test

Tags:

I'm trying to read a file from classpath like this in my unit test:

@Value("classpath:state.json")
Resource stateFile;

I have state.json file in src/test/resources directory. When I try to read this file using stateFile.getInputStream(), it doesn't return any contents. What am I doing wrong?

My test class is annotated like this

@RunWith(SpringRunner.class)
@SpringBootTest

I can see that the code fails if I try with a incorrect file. So I think its seeing the file in classpath but for some reason not reading contents.

like image 689
Nithin Satheesan Avatar asked Apr 15 '17 16:04

Nithin Satheesan


People also ask

How do I load resources from classpath?

We can either load the file(present in resources folder) as inputstream or URL format and then perform operations on them. So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL's and input streams respectively.

How do you get the path of src test resources directory in JUnit?

File class to read the /src/test/resources directory by calling the getAbsolutePath() method: String path = "src/test/resources"; File file = new File(path); String absolutePath = file. getAbsolutePath(); System.


1 Answers

You cant access a @Value resource unless its a property defined. It should be this way.

@Value("${stateJsonPath}")
Resource stateFile;

If you have to get the resource from hardcoded path then use this way.

Resource stateFile = new ClassPathResource("state.json");
like image 91
Praneeth Ramesh Avatar answered Sep 20 '22 13:09

Praneeth Ramesh