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
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:
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);
}
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>
In the command line pass fileName parameter to JVM system properties:
mvn clean test -DfileName=my_file_name.txt
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"));
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"