【问题标题】:JUnit5 parameterized tests at class level类级别的 JUnit5 参数化测试
【发布时间】:2018-02-21 06:06:50
【问题描述】:

是否可以使用 JUnit5 的参数化新特性来运行测试类来接收测试参数,而不是在方法级别进行?

在 JUnit 4 中,@RunWith(Parameterized::class) 之类的运行器加上继承可用于将参数数组传递给子类,但我不确定是否可以使用新的 JUnit 5 api 实现等效的东西。

【问题讨论】:

标签: java kotlin junit5 parameterized-unit-test


【解决方案1】:

简答
没有办法按照 JUnit 4 的风格使用 JUnit 5 参数化 类创建

幸运的是,分离测试逻辑和测试输入数据(参数)的意图可以不同地实现。


JUnit 5 有自己的方法来进行参数化测试,当然,它与 JUnit 4 不同。新方法不允许在类级别使用参数化夹具,即通过其每个测试方法。 所以每个参数化的测试方法都应该用参数链接显式注释。

JUnit 5提供了大量的参数源类型,可以在documentationguides中找到

就您而言,从 Junit 4@Parameters 迁移的最简单方法是使用 @MethodSourceorg.junit.jupiter.params.provider.*@ArgumentsSource

JUnit 4

@RunWith(Parameterized.class)
public class MyTestWithJunit4 {
    @Parameters
    public static Collection<Object[]> data() {
      return Arrays.asList(new Object[][] {     
               { 0, 0, 0 },
               { 1, 2, 3 }, 
               { 5, 3, 8 } 
      });
    }

    int first;
    int second;
    int sum;

    public MyTestWithJunit4(int first, int second, int sum) {
      this.first = first;
      this.second = second;
      this.sum = sum;
    }

    @Test
    public void test() {
      assertEquals(sum, first + second));
    }
}

JUnit 5(带有@MethodSource

class MyTestWithJunit5 {

  @DisplayName("Test with @MethodSource")
  @ParameterizedTest(name = "{index}: ({0} + {1}) => {2})")
  @MethodSource("localParameters")
  void test(int first, int second, int sum) {
    assertEquals(sum, first + second);
  }

  static Stream<Arguments> localParameters() {
    return Stream.of(
        Arguments.of(0, 0, 0),
        Arguments.of(1, 2, 3),
        Arguments.of(5, 3, 8)
    );
  }
}

JUnit 5(带有@ArgumentsSource

class MyTestWithJunit5 {
  @DisplayName("Test with @ArgumentsSource")
  @ParameterizedTest(name = "{index}: ({0} + {1}) => {2})")
  @ArgumentsSource(Params.class)
  void test(int first, int second, int sum) {
    assertEquals(sum, first + second);
  }

  static class Params implements ArgumentsProvider {
    @Override
    public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
      return Stream.of(
          Arguments.of(0, 0, 0),
          Arguments.of(1, 2, 3),
          Arguments.of(5, 3, 8)
      );
    }
  }
}

考虑@MethodSource 中的方法和@ArgumentsSource 中的类可以在任何地方描述,而不仅仅是在测试方法所在的同一个类中。 @MethodSource 还允许提供多个源方法,因为它的 valueString[]

一些评论和比较

JUnit 4 中,我们只能有一个提供参数的工厂方法,并且应该围绕这些参数构建测试。 相反,JUnit 5在绑定参数方面提供了更多的抽象和灵活性,并将测试逻辑与其参数解耦,这是次要的。 这允许独立于参数源构建测试,并在需要时轻松更改它们。

依赖要求

核心junit-jupiter-engine中不包含参数化测试功能, 但位于单独的依赖项junit-jupiter-params

【讨论】:

  • 似乎在 Junit 5 中严重缺乏。我们现在有 Nested 用简短的测试方法测试整个流程,但无法用不同的参数初始化这些流程。
  • 这是对可以做什么的一个很棒的总结,但这并没有足够强调一个可悲的事实(以及问题的实际答案),即在 Junit 5 中无法参数化类创建(以及在 Junit 4 中是可能的。
猜你喜欢
  • 2019-01-23
  • 1970-01-01
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
相关资源
最近更新 更多