Running a Single Unit Test with Maven

Often I need to open a certain project and run one of its unit test from a command line in my terminal window. Not all unit tests but to run a single, specific unit test only. And with this blog post, I am going to share with you how to do it. How to run a single unit test with Maven from a command line.

Let’s say I have a Test class with name UsersServiceImplTest.

Run All Tests in a Class

To all tests in a single test class do these two steps:

  1. Open a terminal window and change directory to your Maven project. You should be in a directory that contains pom.xml file,
  2. Run the below command:
    mvn -Dtest=UsersServiceImplTest test

    where the UsersServiceImplTest is a Test class with test methods.

Run a Single Unit Test

To run a single unit test, do the following:

  1. Open a terminal window and change directory to your Maven project. You should be in a directory that contains pom.xml file,
  2. Run the below command:
    mvn -Dtest=UsersServiceImpl#testCreateUser test

    where the UsersServiceImplTest is a test class and the testCreateUser is a name of a method you are testing.

Run Tests that Match a Pattern

You can also run selected tests in your test class which match a pattern. For example, the command below will run all tests in a test class that start with “testCreate”.

mvn -Dtest=UsersServiceImpl#testCreate* test

I hope this very short maven tutorial on how to run a single unit test was of some value to you. If you would like learn Maven by watching a step by step video lessons, please check the below links.