Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TestWatcher in junit5

Tags:

java

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.

  • Success? Do something
  • Fail? Do something else
like image 549
wyd3x Avatar asked Feb 28 '18 19:02

wyd3x


People also ask

What is TestWatcher in JUnit?

Interface TestWatcher All Superinterfaces: Extension @API(status=EXPERIMENTAL, since="5.4") public interface TestWatcher extends Extension. TestWatcher defines the API for Extensions that wish to process test results. The methods in this API are called after a test has been skipped or executed.

What is @rule in junit5?

@Retention(value=RUNTIME) @Target(value={FIELD,METHOD}) public @interface Rule. Annotates fields that reference rules or methods that return a rule. A field must be public, not static, and a subtype of TestRule (preferred) or MethodRule .

What is @before in junit5?

@BeforeEach is used to signal that the annotated method should be executed before each @Test method in the current test class.


1 Answers

The TestWatcher API was introduced here:

  • https://github.com/junit-team/junit5/pull/1393
  • https://junit.org/junit5/docs/5.4.0/release-notes/

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 {
...
like image 91
Alexis Avatar answered Sep 25 '22 06:09

Alexis