junit5中的TestWatcher

wyd*_*d3x 5 java junit5

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

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

  • 成功?做点什么
  • 失败?做其他事情

小智 8

几天前,TestWatcher被引入Junit 5.4.0:

为了使用它,您必须:

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

TestWatcher为您提供4种方法来对测试中止,失败,成功和禁用执行某些操作:

  • 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
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,将其放在测试中:

@ExtendWith(MyTestWatcher.class)
public class TestSomethingSomething {
...
Run Code Online (Sandbox Code Playgroud)