JUnit5 对@Before* 方法失败做出反应
JUnit5 react to @Before* methods failure
Junit5 中是否有任何钩子可以对 @Before* 方法中的失败做出反应?
我使用@BeforeAll 方法为我的测试初始化环境。但是这种初始化有时可能会失败。我想转储环境,找出问题所在,但我需要在调用 @After* 方法之前完成,这将清除环境并销毁所有信息。
我们在整个测试套件中讨论了数十种这样的 @BeforeAll 方法,因此在每个方法中手动执行它不是一种选择。
我已经尝试过这些,但没有成功:
TestWatcher
对此不起作用,因为它仅在执行实际测试时才会触发。
TestExecutionListener.executionFinished
看起来很有希望,但它在所有 @After 方法之后触发,这对我来说太晚了。
- 我什至尝试在实际清理之前在 @AfterAll 清理方法中执行此操作。但是找不到检测执行了哪些测试或是否有任何失败的方法。
有什么想法吗?
我假设 "fails in @Before* methods" 你的意思是例外?如果是这种情况,您可以按如下方式利用 extension model:
@ExtendWith(DumpEnvOnFailureExtension.class)
class SomeTest {
static class DumpEnvOnFailureExtension implements LifecycleMethodExecutionExceptionHandler {
@Override
public void handleBeforeAllMethodExecutionException(final ExtensionContext context, final Throwable ex)
throws Throwable {
System.out.println("handleBeforeAllMethodExecutionException()");
// dump env
throw ex;
}
}
@BeforeAll
static void setUpOnce() {
System.out.println("setUpOnce()");
throw new RuntimeException();
}
@Test
void test() throws Exception {
// some test
}
@AfterAll
static void tearDownOnce() {
System.out.println("tearDownOnce()");
}
}
日志将是:
setUpOnce()
handleBeforeAllMethodExecutionException()
tearDownOnce()
也就是说,如果 @BeforeAll
方法因异常而失败,则会通知扩展程序。 (请注意,这只是一个 MWE,对于实际的实现,您将提取 DumpEnvOnFailureExtension
并在需要的地方使用它。)
有关详细信息,请查看用户指南中的 "Exception Handling" 部分。
Junit5 中是否有任何钩子可以对 @Before* 方法中的失败做出反应?
我使用@BeforeAll 方法为我的测试初始化环境。但是这种初始化有时可能会失败。我想转储环境,找出问题所在,但我需要在调用 @After* 方法之前完成,这将清除环境并销毁所有信息。
我们在整个测试套件中讨论了数十种这样的 @BeforeAll 方法,因此在每个方法中手动执行它不是一种选择。
我已经尝试过这些,但没有成功:
TestWatcher
对此不起作用,因为它仅在执行实际测试时才会触发。TestExecutionListener.executionFinished
看起来很有希望,但它在所有 @After 方法之后触发,这对我来说太晚了。- 我什至尝试在实际清理之前在 @AfterAll 清理方法中执行此操作。但是找不到检测执行了哪些测试或是否有任何失败的方法。
有什么想法吗?
我假设 "fails in @Before* methods" 你的意思是例外?如果是这种情况,您可以按如下方式利用 extension model:
@ExtendWith(DumpEnvOnFailureExtension.class)
class SomeTest {
static class DumpEnvOnFailureExtension implements LifecycleMethodExecutionExceptionHandler {
@Override
public void handleBeforeAllMethodExecutionException(final ExtensionContext context, final Throwable ex)
throws Throwable {
System.out.println("handleBeforeAllMethodExecutionException()");
// dump env
throw ex;
}
}
@BeforeAll
static void setUpOnce() {
System.out.println("setUpOnce()");
throw new RuntimeException();
}
@Test
void test() throws Exception {
// some test
}
@AfterAll
static void tearDownOnce() {
System.out.println("tearDownOnce()");
}
}
日志将是:
setUpOnce()
handleBeforeAllMethodExecutionException()
tearDownOnce()
也就是说,如果 @BeforeAll
方法因异常而失败,则会通知扩展程序。 (请注意,这只是一个 MWE,对于实际的实现,您将提取 DumpEnvOnFailureExtension
并在需要的地方使用它。)
有关详细信息,请查看用户指南中的 "Exception Handling" 部分。