JUnit 5 @BeforeAll 注解详解

IT 文章2年前 (2023)发布 小编
0 0 0

JUnit 5中的@BeforeAll注解表示一个生命周期方法。@BeforeAll是JUnit 4中@BeforeClass注解的替代者。

1.@BeforeAll注解

@BeforeAll用于标记一个方法,该方法应在当前类中的所有@Test、@RepeatedTest、@ParameterizedTest和@TestFactory方法之前执行一次。默认情况下,测试方法将在与@BeforeAll注解方法相同的线程中执行。

1)@BeforeAll注解的方法必须是测试类中的静态方法。

ad

程序员导航

优网导航旗下整合全网优质开发资源,一站式IT编程学习与工具大全网站

@BeforeAll
public static void init(){
	System.out.println("BeforeAll init() method called");
}

2)或者,如果测试接口或测试类上使用了@TestInstance(Lifecycle.PER_CLASS)注解,我们可以在接口的默认方法上应用此注解。

@TestInstance(Lifecycle.PER_CLASS)
interface TestLifecycleLogger {
    @BeforeAll
    default void beforeAllTests() {
        //
    }
}

如果做不到这一点,JUnit将抛出类型为JUnitException的运行时错误。

org.junit.platform.commons.JUnitException:
@BeforeAll method 'public void com.howtodoinjava.junit5.examples.
JUnit5AnnotationsExample.init()' must be static.
at org.junit.jupiter.engine.descriptor.
LifecycleMethodUtils.assertStatic(LifecycleMethodUtils.java:66)

在父类和子类中,@BeforeAll方法是继承自父类(或接口)的,只要它们没有被隐藏或覆盖。此外,来自父类(或接口)的@BeforeAll方法将在子类的@BeforeAll方法之前执行。

2.@BeforeAll注解示例

让我们举一个例子。我们已经为Calculator类及其add()方法编写了一个测试。我们将使用@RepeatedTest注解来执行这个测试5次。@Repeated注解将导致add测试运行五次。但是,@BeforeAll注解的方法只能调用一次。

ad

AI 工具导航

优网导航旗下AI工具导航,精选全球千款优质 AI 工具集

public class BeforeAllTest {
	@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");
	}
	@BeforeAll
	public static void init(){
		System.out.println("Before All init() method called");
	}
}

我们的Calculator类如下:

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

现在执行测试,你会看到下面的控制台输出:

OutputBefore All init() method called
Running test -> 1
Running test -> 2
Running test -> 3
Running test -> 4
Running test -> 5

很明显,@BeforeAll注解的init()方法只被调用了一次。

© 版权声明

相关文章

暂无评论

暂无评论...