How to Run Maven Test on Specific package/directory

Recently, I ran into a problem with the Jenkins pipeline. Specifically, the Maven tests take too much time to run. I have integration tests and unit tests. The total execution time took more than 30 minutes. In some environments, I only need to run the unit tests, not all the tests.

So I wondered, is there any way that I can run the tests I choose only? That means I can select a single test to run or only run tests in a certain package.

The answer is YES. Let me show you how.

The test structure

To run unit tests and integration tests separately, I split them into two different packages like this:

Split unit test and integration test into two packages
Split unit test and integration test into two packages

Now, if you want to run the tests inside the unit directory only, just execute the following command:

./mvnw -Dtest="com/openexl/apicore/unit/*" test

As you can see, I specified the path to the unit folder (not the package notation i.e. com.openexl.apicore.unit.*)

Sure enough, only tests in that folder were run:

The test ran successfully in the specified package

Running tests in sub-packages

There is one problem with the syntax, it doesn’t run tests in the sub-packages. If, for example, you have more tests in a sub-package like this:

Tests in sub-package

The ones in com.openexl.apicore.unit.another will not run.

To remedy this issue, simply change the execution syntax to this:

./mvnw -Dtest="com/openexl/apicore/unit/**" test

Now if you execute the command, you’ll see all tests are run:

Run tests in sub packages
Run tests in sub-packages

Run tests in specific classes only

There are times you just want to run certain test classes, Maven supports that too. Simply point to the full path to that test class or use regex:

./mvnw -Dtest="*AnotherSampleUnitTest" test
Run tests in specific classes

If instead, you use this pattern:

./mvnw -Dtest="*SampleUnitTest" test

Then all the classes that have names that match that pattern will run:


In this post, we learned how to execute Maven tests in specific class/package/folder. It’s quite handy when you build pipeline using CI/CD (In my case, I use Jenkins).

Leave a Comment