原文: https://howtodoinjava.com/junit5/after-all-annotation-example/

JUnit5 @AfterAll 注解替换了 JUnit4 中的@AfterClass注解。它用于表示应在当前测试类中的所有测试之后执行注解方法

@AfterAll注解用法

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

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

带注解的@AfterAll方法必须是静态方法,否则它将引发运行时错误。

  1. org.junit.platform.commons.JUnitException: @AfterAll method 'public void com.howtodoinjava.junit5.examples.JUnit5AnnotationsExample.cleanUp()' must be static.
  2. at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.assertStatic(LifecycleMethodUtils.java:66)
  3. at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.lambda$findAfterAllMethods$1(LifecycleMethodUtils.java:48)
  4. at java.util.ArrayList.forEach(ArrayList.java:1249)
  5. at java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1080)
  6. at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.findAfterAllMethods(LifecycleMethodUtils.java:48)

@AfterAll注解示例

让我们举个例子。 我使用了一个Calculator类并添加了一个add方法。 我将使用@RepeatedTest注解对其进行 5 次测试。 此注解将导致add测试运行 5 次。 但是@AfterAll带注解的方法只能调用一次。

  1. package com.howtodoinjava.junit5.examples;
  2. import org.junit.jupiter.api.AfterAll;
  3. import org.junit.jupiter.api.AfterEach;
  4. import org.junit.jupiter.api.Assertions;
  5. import org.junit.jupiter.api.DisplayName;
  6. import org.junit.jupiter.api.RepeatedTest;
  7. import org.junit.jupiter.api.RepetitionInfo;
  8. import org.junit.jupiter.api.Test;
  9. import org.junit.jupiter.api.TestInfo;
  10. import org.junit.platform.runner.JUnitPlatform;
  11. import org.junit.runner.RunWith;
  12. @RunWith(JUnitPlatform.class)
  13. public class AfterAnnotationsTest {
  14. @DisplayName("Add operation test")
  15. @RepeatedTest(5)
  16. void addNumber(TestInfo testInfo, RepetitionInfo repetitionInfo)
  17. {
  18. System.out.println("Running test -> " + repetitionInfo.getCurrentRepetition());
  19. Assertions.assertEquals(2, Calculator.add(1, 1), "1 + 1 should equal 2");
  20. }
  21. @AfterAll
  22. public static void cleanUp(){
  23. System.out.println("After All cleanUp() method called");
  24. }
  25. @AfterEach
  26. public void cleanUpEach(){
  27. System.out.println("After Each cleanUpEach() method called");
  28. }
  29. }

其中Calculator类是:

  1. package com.howtodoinjava.junit5.examples;
  2. public class Calculator
  3. {
  4. public int add(int a, int b) {
  5. return a + b;
  6. }
  7. }

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

  1. Running test -> 1
  2. After Each cleanUpEach() method called
  3. Running test -> 2
  4. After Each cleanUpEach() method called
  5. Running test -> 3
  6. After Each cleanUpEach() method called
  7. Running test -> 4
  8. After Each cleanUpEach() method called
  9. Running test -> 5
  10. After Each cleanUpEach() method called
  11. After All cleanUp() method called

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

学习愉快!

源码下载