gpt4 book ai didi

java - 如何避免 '@RepeatedTest Annotation runs BeforeEach and AfterEach in JUnit' ?

转载 作者:行者123 更新时间:2023-11-28 20:48:06 24 4
gpt4 key购买 nike

我在使用 JUnit 5 时遇到以下问题。我想运行 15 次测试,所以我使用了注释 @RepeatedTest(15) 并且它起作用了。但问题是,在每次运行中,它都会调用 @BeforeEach 方法和 @AfterEach 方法。
它对所有 15 个循环都这样做,但它应该只在第一次运行之前调用 @BeforeEach,在最后一次运行之后调用 @AfterEach。我想我不能使用 @BeforeAll@AfterAll 因为我有多个测试,所以这只会在测试 1 和测试 50 之前被调用。

目前运行情况:

@BeforeAll Method
Test 1:
- @BeforeEach Method
- Run1
- @AfterEach Method
- @BeforeEach Method
- Run2
- @AfterEach Method
Test 2:
- @BeforeEach Method
- Run1
- @AfterEach Method
- @BeforeEach Method
- Run2
- @AfterEach Method
@AfterAll Method


它应该如何运行:

@BeforeAll Method
Test 1:
- @BeforeEach Method
- Run1
- Run2
- @AfterEach Method
Test 2:
- @BeforeEach Method
- Run1
- Run2
- @AfterEach Method
@AfterAll Method

最佳答案

我在这里看到四个选项:

  1. 为每个场景创建一个新的测试类,每个场景都有一个@RepeatedTest 方法,并使用@BeforeAll@AfterAll 进行测量。

  2. 不要使用 @RepeatedTest,而是在普通的 @Test 中进行重复和测量。

  3. 让 JUnit 在需要决定执行的地方注入(inject) RepetitionInfo:

    import org.junit.jupiter.api.AfterEach;
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.DisplayName;
    import org.junit.jupiter.api.RepeatedTest;
    import org.junit.jupiter.api.RepetitionInfo;
    import org.junit.jupiter.api.TestInfo;

    class RepeatTest {

    @BeforeEach
    void setUp(RepetitionInfo repetitionInfo, TestInfo testInfo) {
    if (repetitionInfo.getCurrentRepetition() == 1) {
    System.out.println("Before repetition of " + testInfo.getDisplayName());
    }
    }

    @RepeatedTest(value = 3, name = "{displayName}_{currentRepetition}of{totalRepetitions}") @DisplayName("test1")
    void test1(TestInfo testInfo) {
    System.out.println(testInfo.getDisplayName());
    }

    @RepeatedTest(value = 5, name = "{displayName}_{currentRepetition}of{totalRepetitions}") @DisplayName("test2")
    void test2(TestInfo testInfo) {
    System.out.println(testInfo.getDisplayName());
    }

    @AfterEach
    void tearDown(RepetitionInfo repetitionInfo, TestInfo testInfo) {
    if (repetitionInfo.getCurrentRepetition() == repetitionInfo.getTotalRepetitions()) {
    System.out.println("After repetition of " + testInfo.getDisplayName());
    }
    }
    }

    输出:

    Before repetition of test1_1of3
    test1_1of3
    test1_2of3
    test1_3of3
    After repetition of test1_3of3
    Before repetition of test2_1of5
    test2_1of5
    test2_2of5
    test2_3of5
    test2_4of5
    test2_5of5
    After repetition of test2_5of5
  4. 如果您有很多这样的测试,请考虑实现一个小型 JUnit 扩展。也许引入一些新的方法注释。

关于java - 如何避免 '@RepeatedTest Annotation runs BeforeEach and AfterEach in JUnit' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58454348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com