JUnit 5:BeforeEachCallback 和 BeforeTestExecutionCallback 之间的区别

JUnit 5: Difference between BeforeEachCallback and BeforeTestExecutionCallback

我找不到任何资源来解释 JUnit Jupiter 扩展模型中 BeforeEachCallbackBeforeTestExecutionCallback 之间的确切区别。 (我当然也对 "After"-变体感兴趣)

据我了解,以下时间线描述了正在发生的事情:

BeforeEach - BeforeTestExecution - Actual execution of the test - AfterTestExecution - AfterEach

我假设 BeforeTestExecution 存在,因此您可以在处理完所有 BeforeEach 回调之后但在实际测试执行之前执行代码。然而,这对我来说仍然不清楚,因为每个人都可以使用 BeforeTestExecution 而不是 BeforeEach 并且这些回调的执行顺序再次是随机的。

那么 BeforeTestExecution 究竟是为了什么?如果您同时在多个扩展程序中使用此回调会发生什么情况?

Javadocs(here and here) don't make a clear distinction between them but the JUnit5 docs 包括以下内容:

BeforeTestExecutionCallback and AfterTestExecutionCallback define the APIs for Extensions that wish to add behavior that will be executed immediately before and immediately after a test method is executed, respectively. As such, these callbacks are well suited for timing, tracing, and similar use cases. If you need to implement callbacks that are invoked around @BeforeEach and @AfterEach methods, implement BeforeEachCallback and AfterEachCallback instead.

因此,如果您想要 包装测试执行而不进行任何设置,请使用 BeforeTestExecutionCallback。文档继续建议将计时和记录测试执行作为 BeforeTestExecutionCallback.

的可能用例