Search code examples
maven-2surefire

run maven tests from classpath


In order to clean up something of a giant mess, I set out to put the code of my tests all in one ordinary java project (all in src/main/java), and then declare that as a <scope>test</scope> dependency in another project, and expect the tests to run.

No such luck. surefire wants to just run the tests that it can see in the sources.

I can see a sadly obvious solution here involving the build-helper-plugin and adding the tests into the test compilation environment as a source directory, but I was hoping to avoid it.

In case anyone is wondering, the reason for all this is that the POM configuration for use of the failsafe plugin to run some integration tests got so complex that I wanted to split out the compiling of the test classes from the running of the tests.


Solution

  • This is now possible with Maven Surefire v2.15. Simply add the following kind of configuration to the surefire plugin:

    <build>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.15</version>
        <configuration>
          <dependenciesToScan>
            <dependency>com.group.id:my-artifact</dependency>
            <dependency>com.group.id:my-other-artifact</dependency>
          </dependenciesToScan>
          ...
        </configuration>
        ...
      </plugin>
      ...
    </build>
    

    You should also declare the actual dependencies in the dependencies section:

    <dependencies>
      <dependency>
        <groupId>com.group.id</groupId>
        <artifactId>my-artifact</artifactId>
        <type>test-jar</type>
        <version>1.1</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>com.group.id</groupId>
        <artifactId>my-other-artifact</artifactId>
        <type>test-jar</type>
        <version>1.1</version>
        <scope>test</scope>
      </dependency>
    </dependencies>