6

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?

al3c
  • 1,392
  • 8
  • 15

2 Answers2

2

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.

michid
  • 10,536
  • 3
  • 32
  • 59
  • 1
    That's what I wanted! I couldn't find it as it's not in the extension part of the juni5 documentation. – al3c Jan 20 '22 at 11:21
0

Jupiter extensions are meant to be stateless and therefore declare no dependencies on each other.

Want to have feauters of A and B? Create extension C that borrows code from A and B.

Having said that, extensions may communicate with oneself and other extensions via an extension store: https://junit.org/junit5/docs/current/user-guide/#extensions-keeping-state

Sormuras
  • 8,491
  • 1
  • 38
  • 64
  • 3
    Why being stateless means they can't depend on one another? I have 2 depending on 1 storing something in the store and the other one retrieving that. Basically what I"m asking is how to build the "extension C" you mention, if that existed extension B on its own would be useless. – al3c Nov 14 '19 at 17:22