java config_error ai_generated true

生命周期方法执行异常:@BeforeAll 方法 'void setUp()' 必须为静态,除非测试类使用 @TestInstance(Lifecycle.PER_CLASS) 注解

org.junit.jupiter.api.extension.LifecycleMethodExecutionException: @BeforeAll method 'void setUp()' must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS)

ID: java/junit-lifecycle-method-not-static

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2025-02-14首次发现

版本兼容性

版本状态引入弃用备注
8+ active

根因分析

在每次方法生命周期的测试类中,@BeforeAll 或 @AfterAll 方法不是静态的。

English

@BeforeAll or @AfterAll methods are not static in a per-method lifecycle test class.

generic

解决方案

  1. 90% 成功率 Make method static
    @BeforeAll
    static void setUp() {
        // static setup
    }
  2. 85% 成功率 Use @TestInstance(Lifecycle.PER_CLASS)
    @TestInstance(Lifecycle.PER_CLASS)
    class MyTest {
        @BeforeAll
        void setUp() {
            // non-static setup
        }
    }

无效尝试

常见但无效的做法:

  1. Adding static keyword without changing method logic 60% 失败

    Method may access instance fields which are not allowed.

  2. Removing @BeforeAll annotation 70% 失败

    Setup logic won't run, causing test failures.