Often I need to open a certain project and run one of its unit tests 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 will share with you how to do it. How to run a single unit test with Maven from a command line.
For video tutorials on how to do Unit testing and Integration testing of Java applications, please have a look at my video course “Testing Java code with JUnit and Mockito“.
Let’s say I have a Test class with the name UsersServiceImplTest.
Run All Test Methods
It is very easy to run all test methods in a project with mvn test command. There is no more you need to do.
- Open a terminal window,
- Change directory to your Spring Boot project,
- Run the mvn test command.
Run All Tests in a Class
For all tests in a single test class, do these two steps:
- Open a terminal window and change the directory to your Maven project. You should be in a directory that contains pom.xml file,
- 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:
- Open a terminal window and change directory to your Maven project. You should be in a directory that contains pom.xml file,
- 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 starts with “testCreate”.
mvn -Dtest=UsersServiceImpl#testCreate* test
For your project to support running Unit tests with the maven command, add the following dependencies to a <build> section of the pom.xml file.
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>2.22.2</version> </plugin> </plugins> </build>
I hope this very short maven tutorial on running a single unit test was of some value to you. If you would like to learn Maven by watching a step by step video lessons, please check the below links.