Creating and running tests with Maven
Maven provides built-in support for creating and running tests as part of the build process. To create tests in Maven, you can use any of the popular testing frameworks, such as JUnit, TestNG, or Mockito.
Here's an example of a JUnit test class for a simple "Calculator" class:
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calc = new Calculator();
int result = calc.add(2, 3);
assertEquals(5, result);
}
}
To run tests in Maven, you can use the "surefire" plugin, which is included by default in the Maven standard lifecycle. The surefire plugin automatically detects and runs tests in a project's "src/test/java" directory.
To run tests with the surefire plugin, simply run the "test" goal:
mvn test
This will compile the project's main and test sources, and execute all tests in the "src/test/java" directory. The results of the tests will be displayed in the console, along with a summary of the test results.
You can also customize the surefire plugin configuration in your POM file to control how tests are run. For example, you can specify which test classes to include or exclude, or configure test system properties or environment variables.
Here's an example of how to customize the surefire plugin to include only tests with a certain naming pattern:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<includes>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
This configuration specifies that only test classes with a name ending in "Test.java" should be executed.
Leave a Comment