JUnit 5 @AfterAll注解详解

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

JUnit 5中的@AfterAll注解是JUnit 4中@AfterClass注解的替代品。它用于测试类的清理。

@AfterAll注解用于指示在当前测试类的所有测试之后执行带有@AfterAll注解的方法。

请注意,如果您想在每次测试后执行方法,可以使用@AfterEach注解。

1.@AfterAll注解

使用@AfterAll注解一个方法,如下所示:

@AfterAll
public static void cleanUp(){
    System.out.println("After All cleanUp() method called");
}

请记住:

  • 带有@AfterAll注解的方法必须具有void返回类型,并且不能为private。
  • 带有@AfterAll注解的方法可以可选地声明要由ParameterResolvers解析的参数。
  • 从父类继承的@AfterAll方法只要不被隐藏或覆盖,就会一直继承下去。此外,父类中的@AfterAll方法将在子类中的@AfterAll方法之前执行。
  • 带有@AfterAll注解的方法必须是静态方法,否则将抛出运行时错误。
org.junit.platform.commons.JUnitException: @AfterAll method 'public void com.howtodoinjava.junit5.examples.JUnit5AnnotationsExample.cleanUp()' must be static.
    at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.assertStatic(LifecycleMethodUtils.java:66)
    at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.lambda$findAfterAllMethods$1(LifecycleMethodUtils.java:48)
    at java.util.ArrayList.forEach(ArrayList.java:1249)
    at java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1080)
    at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.findAfterAllMethods(LifecycleMethodUtils.java:48)

2.@AfterAll注解示例

让我们通过一个例子来说明。我们使用了Calculator类并添加了一个add方法。我们使用@RepeatedTest注解来测试add方法5次。但是,@AfterAll注解的方法只会被调用一次。

@RunWith(JUnitPlatform.class)
public class AfterAnnotationsTest {
 
    @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");
    }
     
    @AfterAll
    public static void cleanUp(){
        System.out.println("After All cleanUp() method called");
    }
     
    @AfterEach
    public void cleanUpEach(){
        System.out.println("After Each cleanUpEach() method called");
    }
}

其中Calculator类为:

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

运行测试,您将看到以下控制台输出:

Running test -> 1
After Each cleanUpEach() method called
Running test -> 2
After Each cleanUpEach() method called
Running test -> 3
After Each cleanUpEach() method called
Running test -> 4
After Each cleanUpEach() method called
Running test -> 5
After Each cleanUpEach() method called
After All cleanUp() method called

显然,带有@AfterAll注解的cleanUp()方法只被调用一次。


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

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

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