我找不到任何像 TestWatcher 一样替换/工作的注解。
我的目标: 有 2 个函数,它们根据测试结果做一些事情。
- 成功了吗?做点什么
- 失败?做点别的
最佳答案
TestWatcher API介绍在这里:
按如下方式使用:
- 实现
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 {
...
关于java - junit5 中的 TestWatcher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49037406/