Search code examples
mavenjunitmaven-3maven-surefire-pluginjunit5

How to make Maven play nice with JUnit?


The Maven surefire plugin only runs tests which start or end with the word test. This is really cumbersome to deal with in JUnit for 2 reasons:

1 - I already have to add @Test to all my test methods, so also having to append the word test is repetitive.

2 - In JUnit, if I want to disable some test, I just mark it with @Disabled, so if I am using surefire, I will also have to rename the test method.

Are there any ways to make surefire play nice with JUnit? This way, just running what's marked with @Test and automatically ignoring @Disabled methods?


Currently my pom.xml looks like this (only including the test related items to save space):

<packaging>jar</packaging>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.3.2</version>
    <scope>test</scope>
</dependency>

<build>
    <pluginManagement>
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.1</version>
        </plugin>
    </pluginManagement>
</build>

Solution

  • To run JUnit Jupiter tests with Maven you have to use junit-jupiter-engine instead of junit-jupiter-api.

    <dependencies>
        [...]
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.3.2</version>
            <scope>test</scope>
        </dependency>
        [...]
    </dependencies>
    

    You might add the junit-jupiter-api as a supplemental artifact. Furthermore you should use at least maven-surefire-plugin 2.22.1+