Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I wrote a JUnit test that validates the xml returned by a service against its XSD. I initially put the XSD under src/main/resrouces/xsd/<filename>.xsd But now I'm facing the need to move it under webapp, as a static resource, so that it will be publicly accessible when the application is deployed.

I'd rather not have two copies, as I expect that somebody will modify the wrong one sooner or later.

I was loading the file with getClass().getResource("/xsd/<filename>.xsd"), how would I access it if the resource is moved under webapp?

like image 503
acorello Avatar asked Feb 02 '12 15:02

acorello


People also ask

Which methods Cannot be tested by the JUnit test class?

Which methods cannot be tested by the JUnit test class? Explanation: When a method is declared as “private”, it can only be accessed within the same class. So there is no way to test a “private” method of a target class from any JUnit test class.

What happens if JUnit test method is declared as private?

If a JUnit test method is declared as "private", it compiles successfully. But the execution will fail. This is because JUnit requires that all test methods must be declared as "public".

What is a facade in JUnit?

What is a Façade in JUnit? Explanation: Façade defines a higher-level interface that makes the subsystem easier to use.


1 Answers

/src/main/webapp contents are placed on the CLASSPATH when WAR is created and deployed, but not during JUnit tests (both in maven and in my IDE). You have to load them explicitly using:

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

This should work as long as project main directory is the current directory while running tests. Sad but true.

like image 153
Tomasz Nurkiewicz Avatar answered Nov 15 '22 05:11

Tomasz Nurkiewicz