How can I access a static resource in webapp from a JUnit test?

I wrote a JUnit test that checks the xml returned by a service against its XSD. I originally installed XSD under src/main/resrouces/xsd/<filename>.xsd . But now I need to move it under webapp as a static resource so that it is public when the application has been deployed.

I would prefer not to have two copies, as I expect someone to change the wrong one sooner or later.

I uploaded the file using getClass().getResource("/xsd/<filename>.xsd") , how would I access it if the resource was moved to webapp ?

+4
source share
3 answers

In your pom, add it as a resource directory.

 <resources> <resource> <directory>src/main/resources</directory> </resource> <resource> <directory>src/main/webapp</directory> <includes> <include>xsd/schema.xsd</include> </includes> </resource> </resources> 

In use java

 String path = "/xsd/schema.xsd"; InputStream is = getClass().getResourceAsStream(path); 
+3
source

/src/main/webapp content is placed in CLASSPATH when a WAR is created and deployed, but not during JUnit tests (both in maven and in my IDE). You must load them explicitly using:

 new File("src/main/webapp/xsd/<filename>.xsd"); 

This should work as long as the main directory of the project is the current directory during the execution of the tests. Sad, but true.

+3
source

Your resource will still remain in the classpath, so usually load it the way you should continue to work now.

0
source

Source: https://habr.com/ru/post/1394411/


All Articles