JUnit5对@ Before *方法失败做出反应

时间:2020-04-03 11:33:22

标签: junit junit5

@ Before *方法中的Junit5中是否有任何响应失败的钩子?

我使用@BeforeAll方法初始化测试环境。但是此初始化有时可能会失败。我想转储环境,以找出问题所在,但是我需要在调用@ After *方法之前进行操作,这将清除环境并破坏所有信息。

我们在整个测试套件中讨论了许多@BeforeAll方法,因此在每个方法中手动进行操作不是一种选择。

我已经尝试过这些,但是没有运气:

  • TestWatcher对此不起作用,因为只有在执行实际测试时才会触发。
  • TestExecutionListener.executionFinished看起来很有希望,但是它会在所有@After方法之后触发,对我来说太晚了。
  • 我什至尝试在实际清除之前在@AfterAll清除方法中执行此操作。但是找不到方法来检测执行了哪些测试或是否失败。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我认为“ @ Before *方法失败”是指异常吗?在这种情况下,您可以按以下方式利用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"部分。