JUnit 5 @BeforeAll 注解详解

后端 潘老师 6个月前 (10-23) 130 ℃ (0) 扫码查看

JUnit 5中的@BeforeAll注解表示一个生命周期方法。@BeforeAll是JUnit 4中@BeforeClass注解的替代者。

1.@BeforeAll注解

@BeforeAll用于标记一个方法,该方法应在当前类中的所有@Test、@RepeatedTest、@ParameterizedTest和@TestFactory方法之前执行一次。默认情况下,测试方法将在与@BeforeAll注解方法相同的线程中执行。

1)@BeforeAll注解的方法必须是测试类中的静态方法。

@BeforeAll
public static void init(){
    System.out.println("BeforeAll init() method called");
}

2)或者,如果测试接口或测试类上使用了@TestInstance(Lifecycle.PER_CLASS)注解,我们可以在接口的默认方法上应用此注解。

@TestInstance(Lifecycle.PER_CLASS)
interface TestLifecycleLogger {
    @BeforeAll
    default void beforeAllTests() {
        //
    }
}

如果做不到这一点,JUnit将抛出类型为JUnitException的运行时错误。

org.junit.platform.commons.JUnitException:
@BeforeAll method 'public void com.howtodoinjava.junit5.examples.
JUnit5AnnotationsExample.init()' must be static.
at org.junit.jupiter.engine.descriptor.
LifecycleMethodUtils.assertStatic(LifecycleMethodUtils.java:66)

在父类和子类中,@BeforeAll方法是继承自父类(或接口)的,只要它们没有被隐藏或覆盖。此外,来自父类(或接口)的@BeforeAll方法将在子类的@BeforeAll方法之前执行。

2.@BeforeAll注解示例

让我们举一个例子。我们已经为Calculator类及其add()方法编写了一个测试。我们将使用@RepeatedTest注解来执行这个测试5次。@Repeated注解将导致add测试运行五次。但是,@BeforeAll注解的方法只能调用一次。

public class BeforeAllTest {
    @DisplayName("Add operation test")
    @RepeatedTest(5)
    void addNumber(TestInfo testInfo, RepetitionInfo repetitionInfo) {
        System.out.println("Running test -> " + repetitionInfo.getCurrentRepetition());
        Assertions.assertEquals(2, Calculator.add(1, 1), "1 + 1 should equal 2");
    }
    @BeforeAll
    public static void init(){
        System.out.println("Before All init() method called");
    }
}

我们的Calculator类如下:

public class Calculator
{
    public static int add(int a, int b) {
        return a + b;
    }
}

现在执行测试,你会看到下面的控制台输出:

OutputBefore All init() method called
Running test -> 1
Running test -> 2
Running test -> 3
Running test -> 4
Running test -> 5

很明显,@BeforeAll注解的init()方法只被调用了一次。


版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/back/10267.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】