Skip to content

Cannot use @Inject and @TestInstance(TestInstance.Lifecycle.PER_CLASS) #1828

@cristhiank

Description

@cristhiank

Quarkus testing brokes when you mark a @QuarkusTest with @TestInstance(TestInstance.Lifecycle.PER_CLASS) and the test has an @Inject field

https://junit.org/junit5/docs/current/user-guide/#writing-tests-test-instance-lifecycle

This happens because Quarkus is bootstrapped in a @BeforeAll hook

public void beforeAll(ExtensionContext context) throws Exception {
ExtensionContext root = context.getRoot();
ExtensionContext.Store store = root.getStore(ExtensionContext.Namespace.GLOBAL);
ExtensionState state = (ExtensionState) store.get(ExtensionState.class.getName());
PropertyTestUtil.setLogFileProperty();
boolean substrateTest = context.getRequiredTestClass().isAnnotationPresent(SubstrateTest.class);
if (state == null) {
TestResourceManager testResourceManager = new TestResourceManager(context.getRequiredTestClass());
testResourceManager.start();
if (substrateTest) {
NativeImageLauncher launcher = new NativeImageLauncher(context.getRequiredTestClass());
launcher.start();
state = new ExtensionState(testResourceManager, launcher, true);
} else {
state = doJavaStart(context, testResourceManager);
}
store.put(ExtensionState.class.getName(), state);
} else {
if (substrateTest != state.isSubstrate()) {
throw new RuntimeException(
"Attempted to mix @SubstrateTest and JVM mode tests in the same test run. This is not allowed.");
}
}
}

And JUnit's behavior is to instantiate the Test class before calling the @BeforeAll hook.
The class instantiation is done in:
https://github.com/quarkusio/quarkus/blob/master/test-framework/junit5/src/main/java/io/quarkus/test/junit/QuarkusTestExtension.java#L297-L309
and it tries to inject the dependencies but the ArC Container has not been initialized yet (chicken or egg problem)

I have a reproducer in https://github.com/cristhiank/quarkus-bugs

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions