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

Nithin Satheesan :

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.

Collin Krawll :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=460122&siteId=1