How to pass input from command line to junit maven test program

35,362

Solution 1

Passing the numbers as system properties like suggested by @artbristol is a good idea, but I found that it is not always guaranteed that these properties will be propagated to the test.

To be sure to pass the system properties to the test use the maven surefire plugin argLine parameter, like

mvn -Dtest=AddNumbers -DargLine="-Dnum1=1 -Dnum2=2"

Solution 2

To pass input from command line to junit maven test program you follow these steps. For example if you need to pass parameter fileName into unit test executed by Maven, then follow the steps:

  1. In the JUnit code - parameter will be passed via System properties:

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        String fileName = System.getProperty("fileName");
        log.info("Reading config file : " + fileName);
    }
    
  2. In pom.xml - specify param name in surefire plugin configuration, and use {fileName} notation to force maven to get actual value from System properties

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
            <!-- since 2.5 -->
            <systemPropertyVariables>
               <fileName>${fileName}</fileName>
            </systemPropertyVariables>
            <!-- deprecated -->
            <systemProperties>
                <property>
                    <name>fileName</name>
                    <value>${fileName}</value>
                </property>
            </systemProperties>
        </configuration>
    </plugin>
    
  3. In the command line pass fileName parameter to JVM system properties:

    mvn clean test -DfileName=my_file_name.txt
    

Solution 3

You can pass them on the command line like this

mvn -Dtest=AddNumbers -Dnum1=100

then access them in your test with

int num1=Integer.valueOf(System.getProperty("num1"));

Share:
35,362

Related videos on Youtube

Achaius
Author by

Achaius

Updated on July 09, 2022

Comments

  • Achaius
    Achaius almost 2 years

    I wrote a junit test to add two numbers. I need to pass this numbers from command line. I am running this junit test from maven tool as

    mvn -Dtest=AddNumbers
    

    My test program looks like this

    int num1 = 1;
    int num2 = 2;
    
    @Test
    public void addNos() {
      System.out.println((num1 + num2));
    }
    

    How to pass these numbers from command line?

    • Naman
      Naman over 7 years
      can we please have an answer marked here
  • Admin
    Admin about 8 years
    if we need to pass string parameter, how to do it?