Search code examples
cdijunit5quarkusjunit-jupiter

QuarkusTest Access Beans in JUnit5 Extension


I have @QuarkusTest based test class. And I want to implement a JUnit 5 extension (BeforeEachCallback, AfterEachCallback) that interacts with a specific bean of my Quarkus test context. I tried CDI.current(), but that results into: java.lang.IllegalStateException: Unable to locate CDIProvide

In Spring based test for example I access the ApplicationContext via

@Override
  public void beforeEach(final ExtensionContext extensionContext) {
    final ApplicationContext applicationContext = SpringExtension.getApplicationContext(extensionContext);
    MyBean myBean = applicationContext.getBean(MyBean.class);
}

which I can then use to programmatically query concrete beans from my test context. Is there any kind of similar approach to Quarkus tests? I mean, I can @Inject the bean into my test class and access it in a @BeforeEach method, but I am looking for a more 'reusable' solution.

Thank you very much.


Solution

  • geoand put me on the right track. A valid approach would be to use QuarkusTestBeforeEachCallback / QuarkusTestMethodContext.

    So given my custom QuarkusTestBeforeEachCallback implementation which now supports accessing quarkus beans via CDI:

    public class MyBeforeEachCallback implements QuarkusTestBeforeEachCallback {
    
        @Override
        public void beforeEach(QuarkusTestMethodContext context) {
            if (Stream.of(context.getTestInstance().getClass().getAnnotations()).anyMatch(DoSomethingBeforeEach.class::isInstance)) {
                final Object myBean = CDI.current().select(MyBean.class)).get()
                // ... do something with myBean
            }
        }
    
        @Retention(RetentionPolicy.RUNTIME)
        public @interface DoSomethingBeforeEach {
            // ...
        }
    }   
    

    and a service declaration file

    src/test/resources/META-INF/services/io.quarkus.test.junit.callback.QuarkusTestBeforeEachCallback

    with the content

    com.something.test.MyBeforeEachCallback

    I now can use it in my @QuarkusTest tests e.g:

    @QuarkusTest
    @DoSomethingBeforeEach
    public abstract class AbstractV2Test {
    
    // ...
    
    }
    

    This is a bit more complicated than what we are used to with Spring Boot tests, but it definitely works.