Adding Test-Scoped Dependencies

In WeatherFormatterTest, we used a utility from Apache Commons IO—the IOUtils class. IOUtils provides a number of helpful static functions that take most of the work out of input/output operations. In this particular unit test, we used IOUtils.toString() to copy the format-expected.dat classpath resource to a String. We could have done this without using Commons IO, but it would have required an extra six or seven lines of code to deal with the various InputStreamReader and StringWriter objects. The main reason we used Commons IO was to give us an excuse to add a test-scoped dependency on Commons IO.

A test-scoped dependency is a dependency that is available on the classpath only during test compilation and test execution. If your project has war or ear packaging, a test-scoped dependency would not be included in the project’s output archive. To add a test-scoped dependency, add the dependency element to your project’s dependencies section, as shown in Example 4-13.

Example 4-13. Adding a test-scoped dependency

<project>
  ...
  <dependencies>
    ...
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-io</artifactId>
      <version>1.3.2</version>
      <scope>test</scope>
    </dependency>
    ...
  </dependencies>
</project>

After you add this dependency to the pom.xml, run mvn dependency:resolve and you should see that commons-io is now listed as a dependency with scope test. We need to do one more thing before we are ready to run this project’s unit tests: create the classpath resources these unit tests depend on. Dependency scopes are explained in detail in Dependency Scope” in Chapter 8.

Get Maven: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.