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.
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With