Java maven plugin: junit

From wikinotes

The configuration varies between versions of JUnit.

JUnit 5

Documentation

maven surefire docs https://maven.apache.org/surefire/maven-surefire-plugin/plugin-info.html

Usage

mvn test                          # run all tests
mvn test -Dtest=AppTest           # run specific module
mvn test '-Dtest=*Test'           # match modules
mvn test '-Dtest=*#test_*_equal'  # match methods

Requirements

Test modules are run if they match the following

**/Test*.java    // preferred
**/*Test.java
**/*Tests.java
**/*TestCase.java

Configuration

basic configuration

pom.xml configuration


<project ...>
    <!-- junit itself -->
    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.4.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <!-- test runner -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.1</version>
            </plugin>
        </plugins>
    </build>
</project>

Sample JUnit 5 code

package com.example.YourApp;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class Test_YourApp {
    @Test
    void example_assertion()
    {
        Assertions.assertEquals(true, true);
    }
}

Run tests

mvn test                          # run all tests
mvn test -Dtest=AppTest           # run specific module
mvn test '-Dtest=*Test'           # match modules
mvn test '-Dtest=*#test_*_equal'  # match methods

stdout/stderr

NOTE:

If none of these are working,

  • be careful that your test isn't just failing.
  • make sure you are not expecting output from a mock object.


(Option A) stdout/stderr in console (needs configuration)


using CLI params

mvn test -Dsurefire.useFile=false

saved to configuration

<plugin>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>2.10</version>
  <configuration>
    <useFile>false</useFile>
  </configuration>
</plugin>


(Option B) stdout/stderr logfiles (default)


vim target/surefire-reports/<groupId>.<class>-output.txt

(Option C) Configure JUnit5 to allow stdout/stderr (least optimal, but lowest level)

If JUnit is not configured to record stout/stderr, no info will be made accessible to maven-surefire.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.1</version>
    <configuration>
        <junit.platform.output.capture.stdout>true</junit.platform.output.capture.stdout>
        <junit.platform.output.capture.stderr>true</junit.platform.output.capture.stderr>
    </configuration>
</plugin>