在 JUnit 规则 运行 之前使用 Spring TestExecutionListener 初始化状态

Initialize state with a Spring TestExecutionListener before JUnit rules run

我想在每个 Spring 使用 TestExecutionListener 引导 JUnit 测试用例之前初始化状态。此初始化需要 运行 before JUnit @Rules 的相应回调被调用。

我原以为 beforeTestMethod 适合这个,因为它的 JavaDoc 注释说

Pre-processes a test before execution of before lifecycle callbacks of the underlying test framework

规则为测试提供 "before" 回调,所以我预计 beforeTestMethod 在规则之前执行。然而,调试器显示并非如此!


这是我的代码结构:

@RunWith(SpringRunner.class)
@SpringBootTest
@TestExecutionListeners(listeners = MyTestExecutionListener.class, mergeMode = MergeMode.MERGE_WITH_DEFAULTS)
public class MyTest {

    @Autowired
    @Rule
    public MyRule rule;

    @Test
    public void test1() {
        // ...
    }

    // ... more tests
}
public class MyTestExecutionListener implements TestExecutionListener {

    @Override
    public void beforeTestMethod(TestContext testContext) {
        // ...
    }
}
@Component
public class AutoLogin extends ExternalResource {

    @Override
    protected void before() {
        // ...
    }
}

我希望方法按照

的顺序执行

但实际顺序是

知道我做错了什么,或者我应该改用哪种其他 TestExecutionListener 方法吗?

如果您想在 Rule 执行之前为每个测试初始化​​状态,您应该使用 TestExecutionListener 接口的 prepareTestInstance 方法。

@Override
public void prepareTestInstance(TestContext testContext) {
    System.out.println("inside prepareTestInstance");
}

这样您将按以下顺序执行方法:

  • prepareTestInstance()
  • rule.before()
  • test1()

请注意 prepareTestInstance 将在每个测试方法 之前执行