【问题标题】:How to pass input from command line to junit maven test program如何将输入从命令行传递给junit maven测试程序
【发布时间】:2012-04-11 17:23:56
【问题描述】:

我写了一个 junit 测试来添加两个数字。我需要从命令行传递这些数字。我正在从 maven 工具运行这个 junit 测试

mvn -Dtest=AddNumbers

我的测试程序是这样的

int num1 = 1;
int num2 = 2;

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

如何从命令行传递这些数字?

【问题讨论】:

  • 我们可以在这里标记一个答案

标签: maven junit junit4


【解决方案1】:

像@artbristol 建议的那样将数字作为系统属性传递是个好主意,但我发现并不总是保证这些属性会传播到测试中。

为了确保将系统属性传递给测试,请使用maven surefire plugin argLine 参数,例如

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

【讨论】:

    【解决方案2】:

    要将输入从命令行传递到 junit maven 测试程序,请按照以下步骤操作。例如,如果您需要将参数 fileName 传递到 Maven 执行的单元测试中,请按照以下步骤操作:

    1. 在 JUnit 代码中 - 参数将通过系统属性传递:

      @BeforeClass
      public static void setUpBeforeClass() throws Exception {
          String fileName = System.getProperty("fileName");
          log.info("Reading config file : " + fileName);
      }
      
    2. 在 pom.xml 中 - 在surefire插件配置中指定参数名称,并使用 {fileName} 表示法强制 maven 从系统属性中获取实际值

      <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. 在命令行中将 fileName 参数传递给 JVM 系统属性:

      mvn clean test -DfileName=my_file_name.txt
      

    【讨论】:

      【解决方案3】:

      你可以像这样在命令行中传递它们

      mvn -Dtest=AddNumbers -Dnum1=100

      然后在您的测试中使用

      访问它们

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

      【讨论】:

      • 如果需要传字符串参数,怎么办?
      猜你喜欢
      • 2020-09-06
      • 2020-03-02
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多