【问题标题】:JUnit5 ParameterizedTest - Differentiate CsvSource Parameter SetsJUnit5 ParameterizedTest - 区分 CsvSource 参数集
【发布时间】:2018-03-31 06:41:23
【问题描述】:

问题:相同的测试方法用于不同的数据。根据输入数据,测试方法主体应该在断言中期待“等于”或“不等于”。

研究:@ParameterizedTest 允许使用@CsvSource 作为测试方法输入数据:

@ParameterizedTest
@CsvSource({ "foo, 1", "bar, 2", "'baz, qux', 3" })
void testWithCsvSource(String first, int second) {
  assertNotNull(first);
  assertNotEquals(0, second);
}

这可以通过两种相反的测试方法来实现,但它们的代码会非常相似。

QUESTION:如何在方法体中识别,当前使用的是哪一组CsvSource输入参数

【问题讨论】:

  • 正如你提到的,我通常会选择两种测试方法。另一种方法是将预期结果列添加到 CSV 数据中。

标签: unit-testing junit5


【解决方案1】:

您可以使用不同的CsvSource 创建两个测试方法,然后委托给一个通用测试方法。

@ParameterizedTest
@CsvSource({ "foo, 1", "bar, 2", "'baz, qux', 3" })
void testWithCsvSource(String first, int second) {
  internalTest(first, second);
}

@ParameterizedTest
@CsvSource({ "foo2, 1", "bar2, 2", "'baz2, qux2', 3" })
void testWithCsvSource2(String first, int second) {
  internalTest(first, second);
}

private void internalTest(String first, int second) {
  assertNotNull(first);
  assertNotEquals(0, second);
}

【讨论】:

    【解决方案2】:

    目前的最佳解决方案是为每个集合添加索引作为第一个参数:

    @ParameterizedTest
    @CsvSource({
      "0, foo, 11", // Expected to be valid.
      "1, bar, 22",  // Expected to be invalid.
      "2, 'baz, qux', 33" }) // Expected to be invalid.
    void testWithCsvSource(
      int parametersIndex, 
      String first, 
      int second) {
    
      Assertions.assertEquals(
        second.validate(),
        parametersIndex == 0); // Expected true for 0 index parameters only.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      • 2019-02-02
      • 2019-07-14
      • 1970-01-01
      相关资源
      最近更新 更多