0
0
JUnittesting~5 mins

Why extensions customize JUnit behavior

Choose your learning style9 modes available
Introduction

Extensions let you add or change how JUnit runs tests. This helps make tests easier and more powerful without changing JUnit itself.

You want to run some code before or after every test automatically.
You need to add special setup or cleanup steps for certain tests.
You want to change how test results are reported or logged.
You want to add custom rules like retrying failed tests.
You want to inject extra data or objects into your test methods.
Syntax
JUnit
@ExtendWith(MyExtension.class)
public class MyTest {
    // test methods
}

Use @ExtendWith to tell JUnit to use your extension.

Extensions are classes that implement JUnit extension interfaces.

Examples
This example uses a timing extension to measure how long tests take.
JUnit
@ExtendWith(TimingExtension.class)
public class MyTest {
    @Test
    void testSomething() {
        // test code
    }
}
This example shows a retry extension that can rerun a test if it fails.
JUnit
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;

public class RetryExtension implements TestExecutionExceptionHandler {
    @Override
    public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
        // retry logic here
    }
}

@ExtendWith(RetryExtension.class)
public class MyTest {
    @Test
    void testWithRetry() {
        // test code
    }
}
Sample Program

This test class uses a simple extension that prints a message before each test runs.

JUnit
import org.junit.jupiter.api.extension.*;
import org.junit.jupiter.api.*;

class SimpleExtension implements BeforeEachCallback {
    @Override
    public void beforeEach(ExtensionContext context) {
        System.out.println("Before each test: " + context.getDisplayName());
    }
}

@ExtendWith(SimpleExtension.class)
public class MyTest {
    @Test
    void testOne() {
        System.out.println("Running testOne");
        Assertions.assertTrue(true);
    }

    @Test
    void testTwo() {
        System.out.println("Running testTwo");
        Assertions.assertEquals(2, 1 + 1);
    }
}
OutputSuccess
Important Notes

Extensions help keep your test code clean by moving repeated setup or checks outside test methods.

You can combine multiple extensions on one test class.

JUnit provides many built-in extension points to customize behavior.

Summary

Extensions let you add extra behavior to JUnit tests without changing test code.

Use @ExtendWith to apply extensions to test classes or methods.

Extensions can run code before/after tests, handle exceptions, or change test data.