38

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?

oers
  • 18,436
  • 13
  • 66
  • 75
Achaius
  • 5,904
  • 21
  • 65
  • 122

3 Answers3

44

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"
FrVaBe
  • 47,963
  • 16
  • 124
  • 157
20

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
    
Greg Domjan
  • 13,943
  • 6
  • 43
  • 59
Vladimir Kroz
  • 5,237
  • 6
  • 39
  • 50
16

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"));

artbristol
  • 32,010
  • 5
  • 70
  • 103