java TestWatcher在junit5

qxsslcnc  于 2023-08-01  发布在  Java
关注(0)|答案(2)|浏览(136)

我找不到任何注解来替换/像TestWatcher一样工作。
我的目标:有2个功能,做一些事情取决于测试结果。

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

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实现:

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 {
...

kuhbmx9i

kuhbmx9i2#

你可以使用AfterTestExecutionCallback

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
    }

...

}

字符串

相关问题