SAGARFIVE

Tutorials

5.2 Maven Unit testing using Surefire Plugin

  • The Surefire Plugin is used during the test phase of the build lifecycle to execute the unit tests of an application.
  • It generates reports in two different file formats Plain text files (.txt) XML files (.xml)
  • Maven surefire plugin is used to follow the sequence of tests in testng.xml file.
  • If we don’t include the Maven surefire plugin then it will execute all the testcases under src/test/java which has a prefix or suffix as ‘test’ and these tests will get executed without any sequence.
  • maven-surefire-plugin which is used by default whenever the test goal is executed [ with ‘mvn test’ / ‘mvn install’ or ‘mvn clean install’].
  • You can configure this plugin in pom.xml to provide some configuration information like the location of test artifacts [testng.xml] or option to include the conditions(defining group, excluding groups, thread-count, parallelism and skip directly with plugin configuration in pom.xml.
  • Thus you have the choice where to put that information(in pom.xml or in suite testng.xml)
  • All yours unit tests that have an annotation of @test will be executed. But you can also use the plugin to add or exclude tests like such

Task : Running JUnit test class in maven (source 🔗)

(i) Adding JUnit to maven : Adding JUnit dependency in pom.xml

<dependencies>

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

</dependencies>

(ii) Configuring the Maven Surefire Plugin in pom.xml:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
        </plugin>
    </plugins>
</build>

(iii) Writing a simple test case using JUnit framework:

import org.junit.jupiter.api.Test;
 
class JUnit5ExampleTest {
 
    @Test
    void justAnExample() {
 
    }

(iv) Running the test with maven


mvn test or mvn clean test
[INFO]
[INFO] — maven-surefire-plugin:2.22.2:test (default-test) @ running-unit-tests —
[INFO]
——————————————————-
 T E S T S
——————————————————-
Running net.petrikainulainen.junit5.JUnit5ExampleTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.033 sec –
in net.petrikainulainen.junit5.JUnit5ExampleTest
 
Results :
 
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
 
[INFO] ————————————————————————
[INFO] BUILD SUCCESS
[INFO] ————————————————————————

We can also exclude some test class :

<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
    <excludes>
        <exclude>DataTest.java</exclude>
    </excludes>
    <includes>
        <include>DataCheck.java</include>
    </includes>
</configuration>