0
0
JUnittesting~5 mins

Maven Surefire plugin in JUnit

Choose your learning style9 modes available
Introduction

The Maven Surefire plugin runs your tests automatically during the build. It helps check if your code works as expected before you finish your project.

You want to run all your JUnit tests every time you build your project.
You want to see a report showing which tests passed or failed.
You want to run tests only in certain folders or with certain names.
You want to run tests automatically on a continuous integration server.
You want to skip tests temporarily without deleting them.
Syntax
JUnit
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>3.0.0</version>
  <configuration>
    <!-- optional settings here -->
  </configuration>
</plugin>

This XML goes inside the <plugins> section of your pom.xml file.

You can add options inside <configuration> to control which tests run and how.

Examples
Basic setup to run all tests with default settings.
JUnit
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>3.0.0</version>
</plugin>
Run only test classes ending with 'Test.java'.
JUnit
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>3.0.0</version>
  <configuration>
    <includes>
      <include>**/*Test.java</include>
    </includes>
  </configuration>
</plugin>
Skip running tests during the build.
JUnit
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>3.0.0</version>
  <configuration>
    <skipTests>true</skipTests>
  </configuration>
</plugin>
Sample Program

This example shows a simple Calculator class with a test. The Maven Surefire plugin runs the test when you build with mvn test. The test checks if adding 2 and 3 equals 5.

JUnit
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}

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

public class CalculatorTest {
    @Test
    public void testAdd() {
        Calculator calc = new Calculator();
        assertEquals(5, calc.add(2, 3));
    }
}

// pom.xml snippet:
// <plugin>
//   <groupId>org.apache.maven.plugins</groupId>
//   <artifactId>maven-surefire-plugin</artifactId>
//   <version>3.0.0</version>
// </plugin>
OutputSuccess
Important Notes

Surefire automatically finds tests by default if they follow naming patterns like *Test.java or Test*.java.

You can customize which tests run by changing the <includes> and <excludes> in the configuration.

Surefire generates reports in the target/surefire-reports folder after tests run.

Summary

The Maven Surefire plugin runs your tests during the build process.

It helps catch problems early by checking your code automatically.

You configure it in your pom.xml file inside the <plugins> section.