JUnit 5 @AfterEach 注解详解

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

@AfterEach注解用于指示在当前类中的每个@Test、@RepeatedTest、@ParameterizedTest或@TestFactory方法之后执行带有@AfterEach注解的方法。

JUnit 5中的@AfterEach注解是JUnit 4中@After注解的替代品。

默认情况下,测试方法将与带有@AfterEach注解的方法在同一个线程中执行。

1.@AfterEach用法

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

@AfterEach
public void cleanUpEach(){
    //Test cleanup code
}
@Test
void succeedingTest() {
    //test code and assertions
}

带有@AfterEach注解的方法不能是静态方法,否则将抛出运行时错误。

@AfterEach
public static void cleanUpEach(){
    //Test cleanup code
}
//Error
org.junit.platform.commons.JUnitException: @AfterEach method 'public static void com.howtodoinjava.junit5.examples.JUnit5AnnotationsExample.cleanUpEach()' must not be static.

在父类和子类中,@AfterEach方法是继承的,只要它们没有被隐藏或覆盖。

此外,父类(或接口)中的@AfterEach方法将在子类中的@AfterEach方法之后执行。

2.@AfterEach注解示例

让我们通过一个例子来说明。我们使用Calculator类并添加了一个add方法。

我们使用@RepeatedTest注解来运行测试5次。这将导致测试方法(add)运行5次。

对于每次测试方法的调用,带有@AfterEach注解的方法也应该调用一次。

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

很明显,带有@AfterEach注解的cleanUpEach()方法每次测试方法调用时都会调用一次。


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

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

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