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

I just ran into this. I'm using Maven. I took a look at my target/test-classes folder and my resource file wasn't in there (even though it was in my src/test/resources folder).

I ran mvn clean install and then rechecked my target/test-classes folder and the resource file was now there. After that, my test was able to find the file and the test worked.

So it seems that your resources aren't copied until you do a mvn clean. JUnit is looking in the classpath built by maven and until the file actually makes it into the target/test-classes folder, JUnit won't be able to find it.


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");