如何在类级别上重复运行JUnit5测试?

5

我正在使用JUnit5进行集成测试,我有一个用例需要在同一类中重复运行测试,但是我想保持原始测试顺序。是否有方法可以在JUnit5中实现这一点?

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class TestExample {
    final int nrOfIterations = 3;

    @Order(1)
    @DisplayName("One")
    @RepeatedTest(value = nrOfIterations, name = RepeatedTest.LONG_DISPLAY_NAME)
    void repeatedTestWithRepetitionInfo(RepetitionInfo repetitionInfo) {
        System.out.println("One #" + (repetitionInfo.getCurrentRepetition()-1));
        assertEquals(3, repetitionInfo.getTotalRepetitions());
    }

    @Order(2)
    @DisplayName("Two")
    @RepeatedTest(value = nrOfIterations, name = RepeatedTest.LONG_DISPLAY_NAME)
    void repeatedTestWithRepetitionInfoCont(RepetitionInfo repetitionInfo) {
        System.out.println("two #" + (repetitionInfo.getCurrentRepetition()-1));
        assertEquals(3, repetitionInfo.getTotalRepetitions());
    }
}

这将输出:
One #0
One #1
One #2
two #0
two #1
two #2

And I want to get:

One #0
two #0
One #1
two #1
One #2
two #2

测试不应该依赖于执行顺序! - Svetlin Zarev
1
我不同意,单元测试“应该”不包括集成测试,而且使用JUnit5,它不仅是一个单元测试平台了。 - user52028778
1个回答

3

首先我考虑了以下解决方案:

class RepeatTest {
    final int nrOfIterations = 3;

    void test1(int runNr) {
        System.out.println("One #" + runNr);
    }

    void test2(int runNr) {
        System.out.println("Two #" + runNr);
    }

    @RepeatedTest(value = nrOfIterations)
    @TestFactory
    Stream<DynamicNode> factory(RepetitionInfo repetitionInfo) {
        final int runNr = repetitionInfo.getCurrentRepetition() - 1;
        return Stream.of(
                DynamicTest.dynamicTest("One", () -> test1(runNr)),
                DynamicTest.dynamicTest("Two", () -> test2(runNr))
        );
    }    
}

由于 JUnit 5 的限制,这种方法不起作用: 测试方法无法同时使用 RepeatedTest 和 ParameterizedTest 注解。 我能想到的最好方式不太优美,但仍然可以达到您的预期:
@RepeatedTest(value = nrOfIterations)
void repeatedTestWithRepetitionInfo(RepetitionInfo repetitionInfo) {
    final int runNr = repetitionInfo.getCurrentRepetition() - 1;
    test1(runNr);
    test2(runNr);
    assertEquals(3, repetitionInfo.getTotalRepetitions());
}

缺点是只有每个完整重复被显示为单个测试运行,而不是您所请求的每个单独的测试。
我知道这并没有完全回答你的问题,而且我更愿意将其发布为评论,但我没有所需的格式化功能和文本长度;最重要的是,我的解决方案至少部分地达到了您的要求 :)

我不想把所有东西都堆积在一个测试中,但看起来这是目前唯一的选择。希望你的第一个解决方案最终会得到支持。感谢您抽出时间回答。 - user52028778
1
我接受这个答案,因为目前可能没有更好的选择。 - user52028778
@user52028778,我也不高兴,因为没有更好的答案 :( - Honza Zidek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接