How to run Junit test in Maven?

Maven is a project management and comprehension tool that provides a complete build lifecycle framework. User can automate the project's build infrastructure in almost no time as Maven uses a standard directory layout and a default build lifecycle.

To summarize, Maven simplifies and standardizes the project build process. It handles compilation, distribution, documentation, team collaboration and other tasks seamlessly. Maven increases reusability and takes care of most of the build related tasks.

Junit is a testing framework and can use Maven as build tool. It helps to maintain dependencies and their version at one place in pom.xml

User can run junit test cases in maven using surefire plugin.

In this article we will see how to run a junit test cases via surefire.

Approach/Algorithm to solve this problem

  • Step 1: Create a junit classes − JunitTest

  • Step 2: Write a @Test method in the class.

  • Step 3: Now add the junit dependency in pom.xml.

  • Step 4: User can remove testng dependency if not required.

  • Step 5: Now, run it using command line.


The following code to show how to run junit test case in maven:


import org.junit.Test;

public class JunitTest {
    public void testcase1() {
        System.out.println("in test case 1 of junit");


This is a maven configuration file that is used to organize dependencies, plugins and run the junit test cases.

It is very handy when limited tests are needed to execute rather than full suite.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""


        <!-- -->


Command to Run Single class

mvn test 


[INFO] --- maven-surefire-plugin:3.0.0-M5:test (default-test) @ TestNGProjectct ---
[INFO] -------------------------------------------------------
[INFO] -------------------------------------------------------
[INFO] Running JunitTest
in test case 1 of junit
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.625 s - in JunitTest
[INFO] Results:
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.413 s
[INFO] Finished at: 2022-02-14T08:32:09+05:30
[INFO] -------------------------------------------------------------------------

Updated on: 17-Aug-2023


Kickstart Your Career

Get certified by completing the course

Get Started