public class SomeTest {
@RegisterExtension
private final AfterTestExecutionCallback afterTest = context -> {
final Optional<Throwable> exception = context.getExecutionException();
// if you need method name:
// final Method method = context.getRequiredTestMethod();
// one method for error/success:
// after(method, exception);
// or if(exception.isPresent()){}else{})
exception.ifPresentOrElse(this::onError, this::onSuccess);
};
private void onSuccess() {
// Success? Do something
}
private void onError(Throwable throwable1) {
// Fail? Do something else
}
@Test
public void testSomething() {
// put tests here or in a child class
}
...
}
2条答案
按热度按时间zpgglvta1#
这里介绍了TestWatcher API:
使用方法如下:
1.实现
TestWatcher
类(org.junit.jupiter.API.extension.TestWatcher)1.将
@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实现:
字符串
然后你就把这个写进你的测试里:
型
kuhbmx9i2#
你可以使用
AfterTestExecutionCallback
:字符串