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

我只是一个虾纸丫 提交于 2019-12-12 07:09:49

问题


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?


回答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"



回答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
    



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



来源:https://stackoverflow.com/questions/9902084/how-to-pass-input-from-command-line-to-junit-maven-test-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!