junit5 give dependencies between extension
Asked Answered
S

2

7

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?

Synchronous answered 14/11, 2019 at 14:18 Comment(0)
W
4

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.

Wales answered 19/1, 2022 at 10:38 Comment(1)
That's what I wanted! I couldn't find it as it's not in the extension part of the juni5 documentation.Synchronous
V
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

Vedanta answered 14/11, 2019 at 14:31 Comment(1)
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.Synchronous

© 2022 - 2024 — McMap. All rights reserved.