Run Unit Test with Maven Surefire Plugin

The Maven Surefire Plugin is a core Apache Maven plugin that allows us to run the Maven project’s Unit Test. It can also generate reports to help you see how many test passes, how many test failures, and what the causes are for the Unit Test. How is it in details? Let’s learn more about it in this tutorial.

I will create a new Maven project with a simple example with Unit Test as follows:

Run Unit Test with Maven Surefire Plugin

JUnit dependency:

Calculation class:

CalculationTest class:

Now, in Eclipse, if you right-click on the project, select Run As and then select Maven test, and you’ll see the results in the Eclipse Console tab:

Obviously, as you can see, although I did not declare anything related to the Maven Surefire Plugin, it was still called and ran with the  “mvn test” Apache Maven command. That’s because Maven Surefire Plugin is the core plugin for Apache Maven.

Maven Surefire Plugin can work with testing frameworks like JUnit or TestNG. No matter how you use the testing framework, the results of the Unit Test remain the same.

This plugin has only one Maven goal, a “test”. This goal will be run by default during the test phase of the lifecycle build process or when you run the “mvn test” command.

By default, all classes with the name starting with Test or ending with Test, Tests, and TestCase will be picked up to run the Unit Test. As you can see in the example above, the Maven Surefire Plugin automatically picked up the CalculationTest class to run the Unit Test. If you now rename this class to the name not unsatisfactory above conditions, you will not see the Unit Test for the Calculation class being run.

As I said at the beginning, after running the unit test, the Maven Surefire Plugin will generate reports in the target/surefire-reports folder of the project to record the Unit Test results.

Run Unit Test with Maven Surefire Plugin

As you can see, there are two file formats that Maven Surefire Plugin will generate: .txt and .xml.

The Maven Surefire Plugin also allows us to exclude the Unit Test classes that we do not want to run or include classes that write Unit Tests, but the names of these classes do not meet the requirements above. To do this, you have to declare this plugin to your pom.xml file. For example, I exclude, does not run CalculationTest class like this:


5/5 - (1 vote)

Add Comment