【问题标题】:JUnit5 react to @Before* methods failureJUnit5 对 @Before* 方法失败做出反应
【发布时间】:2020-04-03 11:33:22
【问题描述】:

Junit5 中是否有任何钩子对 @Before* 方法中的失败做出反应?

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

我们在整个测试套件中讨论了几十个这样的 @BeforeAll 方法,因此在每个方法中手动执行它不是一种选择。

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

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

有什么想法吗?

【问题讨论】:

    标签: junit junit5


    【解决方案1】:

    我假设“@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" 部分。

    【讨论】:

    • 是的失败我的意思是抛出异常。谢谢,这似乎解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2019-03-15
    • 2017-07-13
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    相关资源
    最近更新 更多