【问题标题】:Junit 5 suite Does not run @BeforeAll and@AfterAllJunit 5 套件不运行@BeforeAll 和@AfterAll
【发布时间】:2022-01-21 19:10:08
【问题描述】:

我有一个带有 @BeforeAll 和 @AfterAll 注释的简单 Junit 5 Siute。套件已执行,但这些方法在所有类执行之前和之后都不会执行。

package demo;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;

@Suite
@SelectClasses({ demo.TestDemoClass1.class, demo.TestDemoClass2.class })

public class TestSuite {

    @BeforeAll
    public static void start() throws Exception {
        System.out.println("Before All from Suite1");
    }

    @AfterAll
    public static void end() throws Exception {
        System.out.println("After All from Suite1");
    }
}`

【问题讨论】:

  • 如果它解决了我的要求,如果你接受它作为答案,我会添加一个答案。
  • 也许你想要一个TestExecutionListener 代替?
  • 您正在混合两种无法混合的东西。从导入的包中可以看出 Suite 是由 Suite 引擎处理的。 Before/AfterAll 来自木星,这就是为什么必须将它们添加到您的测试类中。
  • @johanneslink 套件引擎中没有可使用的注释?我搜索了很多,但套件级别没有任何注释
  • 另外@Lunatic 当我在 Suite 类上添加 ExtendWith 时,您的链接 stackoverflow.com/questions/43282798/… 这里提到的步骤不起作用

标签: java junit5


【解决方案1】:

@BeforeAll 表示被注释的方法应该在当前类中的所有@Test@RepeatedTest@ParameterizedTest@TestFactory方法之前执行;类似于 JUnit 4 的 @BeforeClass。此类方法是继承的(除非它们被隐藏或覆盖)并且必须是静态的(除非使用“每类”测试实例生命周期)。

@AfterAll 也是如此,因此请考虑将 start()end() 方法移至您的 TestDemoClass1TestDemoClass2 类或扩展您的测试类到某个 BaseClass 并将这些方法保留在其中。

public class BaseTest {

    @BeforeAll
    public static void start() throws Exception {
        System.out.println("Before All from Suite1");
    }

    @AfterAll
    public static void end() throws Exception {
        System.out.println("After All from Suite1");
    }
}

还有你的测试课

public class SampleTestOne extends BaseTest {
    @Test
    public void testOne(){
        System.out.println("Extended test passed!");
    }

    @Test
    public void testTwo(){
        System.out.println("Extended test passed!");
    }
}
public class SampleTestTwo extends SampleTestOne {
    @Test
    public void testThree(){
        System.out.println("test passed");
    }
}

最后的结果

或者,您可以创建自定义扩展以在所有测试上下文之前运行代码,这充分解释了here

【讨论】:

  • 扩展基类仍然在套件中的每个类之前和之后执行。我需要它在所有测试之前和所有测试之后执行一次。所以这个解决方案在我的情况下不起作用
  • @AyeshaPathan 不,你错了,如果你创建层次扩展类,你会得到你想要的结果,我将所有的类和结果附加到解决方案中;)
  • 您是否使用 JUNIT 5 来执行上述示例代码。我和你有相同的类结构,我仍然得到下面的结果:来自 Suite1 的所有测试 1 来自 DemoClass 1 的测试 2 来自 DemoClass 1 的测试 2 毕竟来自 Suite1 之前 来自 Suite1 的测试 1 来自 DemoClass 2 的测试 2 来自 DemoClass 2 的测试 2 毕竟来自 Suite1
  • 是的,我愿意!亲爱的 Ayesha,如果您找到了要求,请接受答案。
  • 我知道我的代码有什么问题。我的代码中相同的函数名仅从类 2 执行或全部执行。无论如何,对于我们不希望使用 Suite 执行此操作的情况,我可以接受。我关于在套件级别执行 BeforeAll 和 AfterAll 的原始帖子仍然是一个问题。但这现在可以作为一种解决方法。谢谢@Lunatic!!!
猜你喜欢
  • 1970-01-01
  • 2019-09-09
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 2014-03-10
  • 1970-01-01
  • 1970-01-01
  • 2018-12-26
相关资源
最近更新 更多