【问题标题】:JUnit 5 -- how to make test execution dependent on another test passing?JUnit 5 - 如何使测试执行依赖于另一个测试通过?
【发布时间】:2018-04-12 22:33:21
【问题描述】:

这里的学生。在 JUnit 5 中,根据另一个测试是成功还是失败来实现条件测试执行的最佳方法是什么?我想它会涉及ExecutionCondition,但我不确定如何进行。有没有办法做到这一点,而不必将我自己的状态添加到测试类?

请注意,我知道 dependent assertions,但我有多个 nested tests 代表不同的子状态,因此我想要一种在测试级别本身执行此操作的方法。

例子:

@Test
void testFooBarPrecondition() { ... }

// only execute if testFooBarPrecondition succeeds
@Nested
class FooCase { ... }

// only execute if testFooBarPrecondition succeeds    
@Nested
class BarCase { ... }

【问题讨论】:

    标签: junit junit5


    【解决方案1】:

    @Nested 测试为测试编写者提供了更多的能力来表达 几组测试之间的关系。这种嵌套测试利用 Java 的嵌套类和促进分层思考 测试结构。这是一个详细的示例,都作为源代码 并作为 IDE 中执行的屏幕截图。

    正如JUnit 5 文档所述,@Nested 用于方便地在 IDE 中显示。我宁愿在Depentent Assertions 中使用Assumptions 作为您的先决条件。

    assertAll(
                () -> assertAll(
                        () -> assumeTrue(Boolean.FALSE)
                ),
    
                () -> assertAll(
                        () -> assertEquals(10, 4 + 6)
                )
        );
    

    【讨论】:

      【解决方案2】:

      您可以通过在@BeforeEach/@BeforeAll 设置方法中提取公共前置条件逻辑来解决此问题,然后使用专门为条件测试执行而开发的assumptions。一些示例代码:

      class SomeTest {
      
      @Nested
      class NestedOne {
          @BeforeEach
          void setUp() {
              boolean preconditionsMet = false;
              //precondition code goes here
      
              assumeTrue(preconditionsMet);
          }
      
          @Test // not executed when precodition is not met
          void aTestMethod() {}
      }
      
      @Nested
      class NestedTwo {
          @Test // executed
          void anotherTestMethod() { }
      }
      

      }

      【讨论】:

      • 在建议遵守 Java 命名约定时。类名采用大写。总是。
      • JUnit5 中的测试执行顺序是否明确?
      • @Henrik 尚不支持 JUnit5 中的有序测试执行。他们使用反射来查找方法名称,并且从 Java 7 开始,反射返回的方法的顺序没有定义。我相信他们正在考虑在未来添加某种支持,因为我关注了这个项目,这从 5.0.0 版本中删除了。
      • @Kotse:好的,谢谢。那么建议的解决方案不是问题吗?如果我们不能确保它在我们的测试之前执行,我们怎么能依赖另一个测试的成功呢?
      • @Henrik 由于我们不能依赖另一个测试的成功/失败,因此建议的解决方案是将代码移动到我们可以在测试之前执行的地方。 @BeforeEach 将保证在 NestedOne 类中找到测试之前执行此代码。然后assumeThat()会处理条件执行
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 2016-12-30
      相关资源
      最近更新 更多