toobee
toobee

Reputation: 2752

Run a project build as part of a Unit test?

I have a Java project in which I want to add a Unit test that maven builds a sample project (shaded-jar), runs this created jar and evaluates a written output file.

I am not sure if this is even possible from within a Unit test?

I experienced problems in the past when the unit tests were actually passing but once you created a shaded jar things break due to some dependency issues that seem to only occur in JAR files. I looking for some keywords or even better an example how to do that or how to implement this kind of an integration test.

Upvotes: 0

Views: 138

Answers (1)

Anton Koscejev
Anton Koscejev

Reputation: 4847

As per comment by @khmarbaise:

  1. Add maven-failsafe-plugin to your build to execute integration tests:

    <plugin>
        <artifactId>maven-failsafe-plugin</artifactId>
        <version>2.19.1</version>
        <executions>
            <execution>
                <goals>
                    <goal>integration-test</goal>
                    <goal>verify</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    
  2. Run your jar via maven-exec-plugin. For example:

    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.5.0</version>
        <executions>
            <execution>
                <phase>pre-integration-test</phase>
                <goals>
                    <goal>exec</goal>
                </goals>
                <configuration>
                    <executable>java</executable>
                    <workingDirectory>${project.build.directory}</workingDirectory>
                    <commandlineArgs>-jar ${project.build.finalName}.jar</commandlineArgs>
                </configuration>
            </execution>
        </executions>
    </plugin>
    
  3. Run maven build at least up to verify phase, e.g.: mvn clean verify.

Important notes:

  • Your jar probably doesn't return (doesn't fork into a separate process), so you'll need to use async=true too. Since asyncDestroyOnShutdown defaults to true, it should be stopped up automatically when build ends. If your jar forks, you should stop the forked process via your own manual stop command in post-integration-test phase.
  • This is much easier with war or uber-jar (which include all dependencies within), because otherwise you need to add all dependencies on the classpath as well, which will take additional effort.
  • If you're using something like appassembler-maven-plugin which will handle classpath and startup, you can simply run the output of this plugin instead.

Upvotes: 1

Related Questions