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

前端 未结 3 806
伪装坚强ぢ
伪装坚强ぢ 2020-12-24 11:56

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         


        
相关标签:
3条回答
  • 2020-12-24 12:27

    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
      
    0 讨论(0)
  • 2020-12-24 12:30

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

    0 讨论(0)
  • 2020-12-24 12:42

    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"
    
    0 讨论(0)
提交回复
热议问题