wyd3x
wyd3x

Reputation: 135

TestWatcher in junit5

I can't find any annotation which replace/working the same like TestWatcher.

My goal: Have 2 functions which do something depend on test result.

Upvotes: 12

Views: 11303

Answers (2)

ptanov
ptanov

Reputation: 76

You can do it using 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
    }

...

}

Upvotes: 0

Alexis
Alexis

Reputation: 463

The TestWatcher API was introduced here:

Use it as follows:

  1. Implement TestWatcher class (org.junit.jupiter.api.extension.TestWatcher)
  2. 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 provides you with the following 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)

https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/extension/TestWatcher.html

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

Upvotes: 23

Related Questions