文章目录 1.@AfterEach用法 2.@AfterEach注解示例 @AfterEach注解用于指示在当前类中的每个@Test、@RepeatedTest、@ParameterizedTest或@TestFactory方法之后执行带有@……
文
章
目
录
@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()方法每次测试方法调用时都会调用一次。
还没有评论呢,快来抢沙发~