JUnit5 @BeforeAll注解示例

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

@BeforeAll注解用法

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

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

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

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)
at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.lambda$findBeforeAllMethods$0(LifecycleMethodUtils.java:42)
at java.util.ArrayList.forEach(ArrayList.java:1249)
at java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1080)
at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.findBeforeAllMethods(LifecycleMethodUtils.java:42)

@BeforeAll注解示例

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

package com.howtodoinjava.junit5.examples;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
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 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类是:

package com.howtodoinjava.junit5.examples;

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

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

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

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

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值