本文介绍了junit5中的TestWatcher的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我找不到像TestWatcher一样能替代/工作的任何注释.
I can't find any annotation which replace/working the same like TestWatcher.
我的目标:有2个函数会根据测试结果执行某些操作.
My goal:Have 2 functions which do something depend on test result.
- 成功吗?做点事
- 失败?做其他事情
推荐答案
几天前,TestWatcher被引入Junit 5.4.0:
TestWatcher was introduced to Junit 5.4.0 some days ago:
- https://github.com/junit-team/junit5/pull/1393
- https://junit.org/junit5/docs/5.4.0 /release-notes/
- https://junit. org/junit5/docs/current/api/org/junit/jupiter/api/extension/TestWatcher.html
- https://github.com/junit-team/junit5/pull/1393
- https://junit.org/junit5/docs/5.4.0/release-notes/
- https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/extension/TestWatcher.html
要使用它,您必须:
- 实施
TestWatcher
类(org.junit.jupiter.api.extension.TestWatcher) - 将
@ExtendWith(<Your class>.class)
添加到您的测试类中(我个人使用在每个测试中都扩展的基本测试类)( https://junit.org/junit5/docs/current/user-guide/#extensions )
- Implement
TestWatcher
class (org.junit.jupiter.api.extension.TestWatcher) - Add
@ExtendWith(<Your class>.class)
to your tests classes (I personally use a base test class which I extend in every test) (https://junit.org/junit5/docs/current/user-guide/#extensions)
TestWatcher为您提供4种方法,用于在测试中止,失败,成功和禁用时做某事:
TestWatcher provides you with 4 methods to do something on test abort, failed, success and disabled:
-
testAborted(ExtensionContext context, Throwable cause)
-
testDisabled(ExtensionContext context, Optional<String> reason)
-
testFailed(ExtensionContext context, Throwable cause)
-
testSuccessful(ExtensionContext context)
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实施示例:
Sample TestWatcher implementation:
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
}
}
然后您将其放在测试中:
Then you just put this on your tests:
@ExtendWith(MyTestWatcher.class)
public class TestSomethingSomething {
...
这篇关于junit5中的TestWatcher的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!