在junit5中的TestWatcher

时间:2018-02-28 19:45:44

标签: java junit5

我无法找到替换/工作相同的注释,如TestWatcher。

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

  • 成功?做点什么
  • 失败?做别的事

1 个答案:

答案 0 :(得分:2)

几天前,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
    }
}

然后您将其放在测试中:

@ExtendWith(MyTestWatcher.class)
public class TestSomethingSomething {
...
相关问题