我找不到像TestWatcher一样可以替代/工作的任何注释。

我的目标:
有2个功能取决于测试结果。

  • 成功吗?做些
  • 失败?做其他事情
  • 最佳答案

    此处介绍了TestWatcher API:

  • https://github.com/junit-team/junit5/pull/1393
  • https://junit.org/junit5/docs/5.4.0/release-notes/

  • 如下使用它:
  • 实现TestWatcher类(org.junit.jupiter.api.extension.TestWatcher)
  • @ExtendWith(<Your class>.class)添加到您的测试类中(我个人使用在每个测试中都扩展的基本测试类)(https://junit.org/junit5/docs/current/user-guide/#extensions)

  • TestWatcher为您提供以下方法来对测试中止,失败,成功和禁用执行某些操作:
  • testAborted​(ExtensionContext context, Throwable cause)
  • testDisabled​(ExtensionContext context, Optional<String> reason)
  • testFailed​(ExtensionContext context, Throwable cause)
  • testSuccessful​(ExtensionContext context)

  • https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/extension/TestWatcher.html

    示例TestWatcher实现:
    import java.util.Optional;
    
    import org.junit.jupiter.api.extension.ExtensionContext;
    import org.junit.jupiter.api.extension.TestWatcher;
    
    public class MyTestWatcher implements TestWatcher {
        @Override
        public void testAborted(ExtensionContext extensionContext, Throwable throwable) {
            // do something
        }
    
        @Override
        public void testDisabled(ExtensionContext extensionContext, Optional<String> optional) {
            // do something
        }
    
        @Override
        public void testFailed(ExtensionContext extensionContext, Throwable throwable) {
            // do something
        }
    
        @Override
        public void testSuccessful(ExtensionContext extensionContext) {
            // do something
        }
    }
    

    然后,将其放在测试中:
    @ExtendWith(MyTestWatcher.class)
    public class TestSomethingSomething {
    ...
    

    10-04 18:04