Maven Surefire plugin in JUnit - Build an Automation Script
package com.example; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class CalculatorTest { @Test void addition_shouldReturnCorrectSum() { Calculator calc = new Calculator(); int result = calc.add(2, 3); assertEquals(5, result, "2 + 3 should equal 5"); } } // Calculator.java package com.example; public class Calculator { public int add(int a, int b) { return a + b; } } // pom.xml snippet for Surefire plugin /* <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0</version> </plugin> </plugins> </build> */
This code defines a simple JUnit 5 test class CalculatorTest with one test method addition_shouldReturnCorrectSum. It tests the add method of the Calculator class.
The test uses assertEquals to check that adding 2 and 3 returns 5. This assertion ensures the test passes only if the method works correctly.
The pom.xml snippet shows how to configure the Maven Surefire plugin version 3.0.0, which runs the JUnit tests when you execute mvn test.
Running mvn test in the project directory will invoke Surefire, which finds and runs the test, then reports the result in the console.
This setup follows best practices: using JUnit 5 annotations, clear assertions, and proper Maven plugin configuration.
Now add data-driven testing with 3 different input pairs for the add method