I am running into trouble with JUnit 5 (5.0 or 5.1) and custom extension.
We are using service loader to load all implementations which then modify how our extension is bootstrapped. These implementations can be loaded just once, so I was thinking of using ExtensionContext.Store
and placing it there. Every subsequent test instance would then just load it from Store
instead of via service loader.
Now, I am even aware of the hierarchical context structure and I know that there is some "root" context which you can get through ExtensionContext.getRoot()
. But this "root" context (instance of JupiterEngineExtensionContext
) isn't really root - there is different one for every test instance.
Say you have FooTest
and BarTest
, then printing out getRoot()
for each of them yields:
org.junit.jupiter.engine.descriptor.JupiterEngineExtensionContext@1f9e9475
org.junit.jupiter.engine.descriptor.JupiterEngineExtensionContext@6c3708b3
And hence trying to retrieve previously stored information from Store
fails.
- Is having this limitation intended? It makes the borderline between
ClassExtensionContext
andJupiterEngineExtensionContext
pretty blurred. - Is there another way to globally store some information via extension?
Here is a (very) simplified version of how I tried working with the store (cutting out all other information basically). I also added some System.out.print()
calls to underline what I am seeing. Executing this extension on two test classes results in what I described above:
public class MyExtension implements BeforeAllCallback {
@Override
public void beforeAll(ExtensionContext context) throws Exception {
System.out.println(context.getRoot());
if (context.getRoot().getStore(Namespace.create(MyExtension.class)).get("someIdentifier", String.class) == null) {
context.getRoot().getStore(Namespace.create(MyExtension.class)).put("someIdentifier", "SomeFooString");
} else {
// this is never executed
System.out.println("Found it, no need to store anything again!");
}
}
}
EDIT: Here is a minimal project on GH(link), run by mvn clean install
, which displays the behaviour I see.