rob
rob

Reputation: 6247

What is the recommended way to execute code at the end of the test phase in Maven?

I have some JUnit tests that execute in parallel in the test phase and output one .json file per test, and I want to call a custom Java method to do some aggregation and post-processing on those files after all of the tests have finished executing.

The integration-test phase is followed by the post-integration-test phase in the default Maven lifecycle, but the test phase is not followed by a post-test phase, and I would prefer not to abuse some other phase for this purpose.

Question: What is the recommended way to post-process the results at the end of the test phase?

Upvotes: 1

Views: 558

Answers (1)

A_Di-Matteo
A_Di-Matteo

Reputation: 27862

As well described in another SO post, there is no post-test phase in Maven for good reasons (mainly, unit test is unit test).

However, in your case you don't need to create an additional Maven plugin, which would probably solve the issue but also add an additional layer of complexity in terms of maintenance, testing, sharing.

Since you already have the required code in a Java method - as mentioned in the question - it would probably make more sense to use the Exec Maven Plugin and its java goal.

You could hence simply add to your POM:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.1.1</version>
    <executions>
        <execution>
            <phase>test</phase> <!-- executed as post-test, that is, after Surefire default execution -->
            <goals>
                <goal>java</goal>
            </goals>
            <configuration>
                <mainClass>com.sample.JsonFileAggregator</mainClass> <!-- your existing Java code, wrapped in a main -->
                <arguments>
                    <argument>${project.build.directory}</argument> <!-- directory from where to load json files -->
                </arguments>
                <classpathScope>test</classpathScope> <!-- if your Java code is in test scope -->
            </configuration>
        </execution>
    </executions>
</plugin>

That is, binding its execution to the test phase, Maven will executed it after any default binding (hence after the default Maven Surefire execution) and as such executed as a post-test.

Your existing Java code can then be invoked via a crafted (if not already existing) Java main, potentially passing to it arguments (like the directory from where to load the .json files, in the snippet above to the target folder, via its standard property ${project.build.directory}, as an example). Moreover, as mentioned in the snippet, your Java code may be located in test scope (that is, under src/test/java), hence to make it visible you would need to also configure the classpathScope accordingly.

Upvotes: 1

Related Questions