Running Single Unit Test or Method Using Maven

In this blog post we will see how to run single Unit test or method when using Maven as build tool and maven surefire plugin to run unit tests.

Running Unit Tests

You can use following command to run all the test

mvn testCode language: Java (java)

Running a Single Test

IDE’s like IntelliJ Idea and Eclipse allow you to run single unit test or method from GUI.Now let’s see how to run single test or method from commnadline using Maven.

During your development phase, you might want to run single unit test case repeatedly instead of running all the test cases every time.

To run the single test with Maven use the -Dtest=<Test-Name> option like below

mvn test -Dtest=EmployeeControllerTestCode language: Java (java)

The value for the test parameter is the name of the test class

You can also use pattern to run multiple tests

mvn test -Dtest=Employee*TestCode language: Java (java)

You may use multiple names/patterns, separated by commas:

mvn test -Dtest=EmployeeControllerTest, Department*TestCode language: Java (java)

You can also use package names or wild cards in pattern matching.

mvn test -Dtest="dev/fullstackcode/EmployeeControllerTest", "**/Department*Test" Code language: Java (java)

Running Selected Methods in a Single Test Class

Starting from Surefire plugin version 2.7.3 , we can also run only selected methods from a test case.

mvn test -Dtest=EmployeeControllerTest#testMethodCode language: Java (java)

You can also use pattern

mvn test -Dtest=EmployeeControllerTest#testMethod*Code language: Java (java)

Starting from Surefire plugin version 2.19, we can also select multiple methods

mvn test -Dtest=EmployeeControllerTest#testMethod1+testmethod2Code language: Java (java)

Using Multiple Formats in Single Command

From Surefire Plugin 2.19 in a single command we can set inclusion and exclusion of test cases.

mvn test "-Dtest=???Test, !Unstable*, pkg/**/Ci*leTest.java, *Test#test*One+testTwo?????, #fast*+slowTest" Code language: Java (java)
mvn "-Dtest=Basic*, !%regex[.*.Unstable.*], !%regex[.*.MyTest.class#one.*|two.*], %regex[#fast.*|slow.*]" testCode language: Java (java)

  • The file extensions are not mandatory in non-regex patterns , and packages with slash can be used
  • The exclamation mark (!) excludes tests.
  • The character (?) within non-regex pattern replaces one character in file name or path.
  • The regex validates fully qualified class file, and validates test methods separately after (#) however class is optional. 
  •  The regex supports ‘.class’ file extension only

Note : The regex comments, marked by (#) character, are unsupported

Similar Posts