junit5junit5-extension-model

junit5 give dependencies between extension


I've just started writing some junit5 tests and extensions.

I've quite quickly hit what I think is an issue: how do I tell junit5 that ExtensionB requires ExtensionA to be present?

For example I have a 'base' extension ExtensionA which starts a database and does some initialization and that's enough for some tests.

I also have ExtensionB which 'requires' some of the work done by ExtensionA, mostly getting some objects from the store and then resolving some parameters.

Obviously whenever I want extension B I also need extension A to be present. Is there a way to force that? I've tried annotating with @ExtendWith(A.class) class ExtensionB but that seems to have no effect.

Is there a way to achieve what I need?

Or I'm just using junit5 in the wrong way and should just have a single extension which does everything for me?


Solution

  • Declare a composed annotation to combine multiple annotations in a reusable way:

    @Target({ ElementType.TYPE, ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    @ExtendWith({ DatabaseExtension.class,  WebServerExtension.class })  
    public @interface DatabaseAndWebServerExtension {}
    

    The extensions are registered in the order they are declared.

    You can then use this annotation instead of the two individual ones:

    @DatabaseAndWebServerExtension
    public class MyDbTest {}
    

    See the section on declarative extension registration in the JUnit 5 User Guide on the exact semantics.