2

I've seen several variations of this question on StackOverflow, but none describe my scenario exactly, or offer a solution that works for me.

I'm building a Java EE web game. I'm using JUnit to do unit testing during the build process. In my webapp folder, I have assets that users access via HTTP GET requests. In my source code, I have corresponding Java classes that implement the logic of those assets.

For example, I have a class called CookingPot, which implements the logic for a cooking pot in my game. In the webapp folder, I have a files that provide media and content for cooking pots to the user, for example:

webapp/assets/items/CookingPot.svg (an image of the cooking pot)
webapp/assets/items/CookingPot.html (an HTML description of the cooking pot)

During unit testing, I'd like to make sure that for every game item (in this example, the CookingPot item), there is an SVG and HTML file in the correct place in the webapp folder.

How can I implement this test? The JUnit tests are executed in the Maven build environment, which does not provide a Tomcat server to test against, so accessing them via HTTP won't work. I've tried:

URL svg = getClass().getResource("/webapp/assets/items/CookingPot.svg");
URL svg = getClass().getResource("webapp/assets/items/CookingPot.svg");

But those return null.

I have a feeling that there is something simple I'm missing here, but I don't know what it is. Surely there's got to be a way to test that these files exist during the build process?

Thanks in advance for any help!

Tim Gustafson
  • 177
  • 1
  • 11

1 Answers1

3

The src/main/webapp folder is not part of the classpath (per default). Hence you can't access them with the code you provide in your question. If your files would be part of src/main/resources you could access them with .getResource("") from your Unit test without further configuration.

Modifying the Surefire plugin and including the webapp folder can solve your issue using your current setup (like mentioned here: Unit Test in Maven requires access to the src/main/webapp Directory):

  <plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.2</version>
    <configuration>
      <additionalClasspathElements>
        <additionalClasspathElement>src/main/webapp</additionalClasspathElement>
      </additionalClasspathElements>
    </configuration>
  </plugin>
rieckpil
  • 10,470
  • 3
  • 32
  • 56