在junit 5中,若需在整个测试类开始前执行一次初始化逻辑,应使用 @beforeall 注解。该注解标记的方法必须是静态的(除非使用 @testinstance(lifecycle.per_class)),且通常用于设置共享资源或一次性配置。调用后,所有测试方法将基于此状态运行。

@BeforeAll 与 @BeforeEach 的执行顺序区别是什么
@BeforeAll 在测试类的所有测试方法执行前运行一次,而 @BeforeEach 在每个测试方法执行前都会运行。前者适合耗时操作如数据库连接,后者适合重置测试环境。

import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
public class OrderServiceTest {
private static OrderService service;
private Order order;
@BeforeAll
static void initOnce() {
// 仅执行一次:初始化服务实例
service = new OrderService();
System.out.println("Service initialized once");
}
@BeforeEach
void setUp() {
// 每个测试前执行:创建新订单对象
order = new Order("Item-001", 10.0);
System.out.println("Order created for test");
}
@Test
void testCalculateTotal() {
double total = service.calculateTotal(order);
assertEquals(10.0, total);
}
@Test
void testGetItemId() {
assertEquals("Item-001", order.getId());
}
}预期输出包含两行 "Service initialized once"(仅一次)和两行 "Order created for test"(每测试一次)。这验证了 @BeforeAll 的全局性与 @BeforeEach 的局部性。
非静态 @BeforeAll 方法如何正确声明
默认情况下 @BeforeAll 必须为静态方法。若需访问实例字段,需在类上添加 @TestInstance(Lifecycle.PER_CLASS),此时 @BeforeAll 可声明为非静态。
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class UserRepoTest {
private UserRepository repo;
@BeforeAll
void initInstance() {
// 非静态初始化,可访问实例成员
repo = new UserRepository();
repo.connect();
}
@Test
void testFindUser() {
assertNotNull(repo.findById(1L));
}
}该代码展示了通过 @TestInstance 改变生命周期后,@BeforeAll 方法无需 static 关键字即可直接操作实例变量 repo。
当 @BeforeAll 抛出异常时后续测试会怎样
如果 @BeforeAll 方法中抛出未捕获的异常,整个测试类将被跳过,不会执行任何 @Test 方法。这是为了确保在基础环境未就绪时不运行无效测试。

















