JUnit 5 @AfterEach 注解

JUnit 5 @AfterEach 注释替代了 JUnit 4 中的 @After注释。

它用于表示应在当前类中的每个 @Test方法之后执行带注释的方法。

更多: zhilu jiaocheng

@AfterEach 注释示例

让我们举个例子。
我使用了一个 Calculator类并添加了一个 add方法。
我将使用 @RepeatedTest注释对其进行 5 次测试。
此注释将导致 add测试运行 5 次。
对于每次运行测试方法,@AfterEach注释方法也应该每次运行。

package com.onitroad.junit5.examples;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.RepetitionInfo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
@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 类是:

package com.onitroad.junit5.examples;
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 注释用法

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

@AfterEach
public void cleanUpEach(){
	System.out.println("After Each cleanUpEach() method called");
}

@AfterEach注释方法不能是静态方法,否则会抛出运行时错误。

org.junit.platform.commons.JUnitException: @AfterEach method 'public static void com.onitroad.junit5.examples.JUnit5AnnotationsExample.cleanUpEach()' must not be static.
	at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.assertNonStatic(LifecycleMethodUtils.java:73)
	at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.lambda$findAfterEachMethods(LifecycleMethodUtils.java:60)
	at java.util.ArrayList.forEach(ArrayList.java:1249)
	at java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1080)
	at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.findAfterEachMethods(LifecycleMethodUtils.java:60)
日期:2020-09-17 00:09:51 来源:oir作者:oir