The @ExtendWith annotation tells JUnit to use extra code called extensions when running tests. This helps add features like setup, cleanup, or special checks.
0
0
@ExtendWith annotation in JUnit
Introduction
When you want to add custom setup or cleanup steps before or after tests run.
When you need to change how tests behave, like retrying failed tests automatically.
When you want to integrate with other tools, like mocking frameworks or dependency injection.
When you want to add logging or timing around your tests.
When you want to handle exceptions or test conditions in a special way.
Syntax
JUnit
@ExtendWith(ExtensionClass.class)Place @ExtendWith above your test class or test method.
You can use multiple extensions by listing them in an array: @ExtendWith({Ext1.class, Ext2.class}).
Examples
This applies
MyExtension to all tests in MyTest class.JUnit
@ExtendWith(MyExtension.class) public class MyTest { // test methods }
This applies two extensions to the test class.
JUnit
@ExtendWith({ExtensionOne.class, ExtensionTwo.class})
public class MultiExtensionTest {
// test methods
}This applies the extension only to a single test method.
JUnit
@ExtendWith(MyExtension.class)
@Test
public void testSomething() {
// test code
}Sample Program
This test class uses @ExtendWith to add SimpleExtension. The extension prints a message before each test runs. The test methods print their own messages.
JUnit
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; class SimpleExtension implements BeforeEachCallback { @Override public void beforeEach(ExtensionContext context) throws Exception { System.out.println("Before each test: Setup done."); } } @ExtendWith(SimpleExtension.class) public class ExtensionTest { @Test void testOne() { System.out.println("Running testOne"); } @Test void testTwo() { System.out.println("Running testTwo"); } }
OutputSuccess
Important Notes
Extensions can modify test behavior without changing test code.
Use @ExtendWith to keep tests clean and reusable.
JUnit provides many built-in extensions you can use or customize.
Summary
@ExtendWith adds extra behavior to tests using extensions.
Use it on classes or methods to run code before, after, or around tests.
It helps keep tests simple and powerful by reusing common logic.