JUnit5 @BeforeAll 注解替換了 JUnit4 中的@BeforeClass注解。 它用于表示應在當前測試類中的所有測試之前執行注解方法。
junit常用注解?@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");}@BeforeAllpublic 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()僅被調用一次。
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态