Junit 5 TestWatcher

Junit 5 provides a lot of ways to extend the functionality provided by default. if we want to extend and execute custom code after JUnit 5 test case for that JUnit 5 provides us TestWatcher interface.

TestWatcher interface which has 4 default method.

  • testAborted
  • testDisabled
  • testFailed
  • testSuccessful
package com.example.junit5.sujan;

public class AppleCalculator {
    public boolean booleanApple(String appleText) {
        return "apple".equals(appleText);
    }
}
package com.example.junit5.sujan;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

@ExtendWith(MyTestWatcher.class)
class AppleCalculatorTest {
    @Test
    void assertTrueTest() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertTrue(appleCalculator.booleanApple("apple"));
    }

    @Test
    void assertFalseTest() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertFalse(appleCalculator.booleanApple("apple"));
    }

    @Test
    @Disabled
    void disabledTest() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertFalse(appleCalculator.booleanApple("apple"));
    }
}
package com.example.junit5.sujan;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestWatcher;

import java.util.Optional;

public class MyTestWatcher implements TestWatcher {
    @Override
    public void testAborted(ExtensionContext extensionContext, Throwable throwable) {
        System.out.println("MyTestWatcher.testAborted");
        System.out.println("extensionContext = " + extensionContext);
        System.out.println("throwable = " + throwable);
    }

    @Override
    public void testDisabled(ExtensionContext extensionContext, Optional<String> optional) {
        System.out.println("MyTestWatcher.testDisabled");
        System.out.println("extensionContext = " + extensionContext);
        System.out.println("optional = " + optional);
    }

    @Override
    public void testFailed(ExtensionContext extensionContext, Throwable throwable) {
        System.out.println("MyTestWatcher.testFailed");
        System.out.println("extensionContext = " + extensionContext);
        System.out.println("throwable = " + throwable);
    }

    @Override
    public void testSuccessful(ExtensionContext extensionContext) {
        System.out.println("MyTestWatcher.testSuccessful");
        System.out.println("extensionContext = " + extensionContext);
    }
}
plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
}
test {
    useJUnitPlatform()
    testLogging {
        events "passed", "skipped", "failed"
    }
}

 

follow us on