acorello
acorello

Reputation: 4653

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?

Upvotes: 5

Views: 1579

Answers (3)

Usman Ismail
Usman Ismail

Reputation: 18679

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 java use

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

Upvotes: 3

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340763

/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.

Upvotes: 5

Kurt Du Bois
Kurt Du Bois

Reputation: 7665

Your resource will still remain on the classpath, so normally loading it the way you now do should keep working.

Upvotes: 0

Related Questions