javaunit-testingjunitjunit5junit5-extension-model

How to create custom JUnit5 Extensions


Is it possible to create a custom extension like I could've created a @Rule in JUnit4?

public class MockMetadataServiceRule extends ExternalResource {   
    @Override
    protected void before() throws Throwable {
        //some setup
    }

    @Override
    protected void after() {
       // some teardown
    }
}

Then, I can do this with inside the test class with JUnit5

@BeforeAll
public static void init() {
    MetadataServiceFactory.setService(MockitoMockMetadataService.getMock());
}

@AfterAll
public static void teardown() {
    MetadataServiceFactory.setService(null);
}

but I presume you can @ExtendWith(MyExtension.class) now?

EDIT: The example of my extension in case @nullpointer link disappeared. Thanks.

public class MockMetadataServiceExtension implements BeforeAllCallback, AfterAllCallback {

    @Override
    public void afterAll(ExtensionContext extensionContext) throws Exception {
        MetadataServiceFactory.setService(null);
    }

    @Override
    public void beforeAll(ExtensionContext extensionContext) throws Exception {
        MetadataServiceFactory.setService(MockitoMockMetadataService.getMock());
    }
}

Solution

  • Yes. It's possible to create custom extensions in Junit5. In fact that is what @ExtendWith is intended for :

    To register a custom YourExtension for all tests in a particular class and its subclasses, you would annotate the test class as follows.

    @ExtendWith(YourExtension.class)
    class YourTests {
        // ...
    }
    

    An example fo the BeforeAllCallback, AfterAllCallback could be found at spring-framework.


    Multiple extensions can be registered together like this:

    @ExtendWith({ YourExtension1.class, YourExtension2.class })
    class YourTests {