Execute single JUnit Test using command line in Java

Overview

In this post, we are going to learn how to run single JUnit Test using command line in Java. There may be many test cases in a single Java file/class so that sometimes we may need to execute a particular test method only.

We may have many test cases that might be implemented in multiple methods of a class.

So, instead of executing all the JUnit test we want to execute a single test.

run a single JUnit Test using  command line in Java

Solution to run single JUnit Test using command line in Java

Let’s take a look on the following class.

public class UserTest{
    @Test
    public void shouldCreateUser(){
        // Implementation
    }
    @Test
    public void shouldReturnUser(){
        // Implementation
    }
}

In the above class, when we execute maven test command like following:

mvn test -Dtest=UserTest

Then, the both method will be executed. In fact, if there are 10 test cases then all the 10 test cases will be executed. This may not be good all the time. Right?

So, if you want to execute shouldCreateUser method then you can use the following command.

mvn test -Dtest=UserTest#shouldCreateUser

Above code should run the test shouldCreateUser and other test will be skipped.

Conclusion

In this post, we learn to execute single test using maven command.

Thanks


Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments