QuarkusTest 访问 JUnit5 扩展中的 Bean

Phi*_* Li 5 cdi junit5 junit-jupiter quarkus

我有@QuarkusTest基础测试班。我想实现一个 JUnit 5 扩展(BeforeEachCallback、AfterEachCallback),它与 Quarkus 测试上下文的特定 bean 交互。我尝试过CDI.current(),但结果是:java.lang.IllegalStateException: Unable to locate CDIProvide

例如,在基于 Spring 的测试中,我通过访问 ApplicationContext

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

然后我可以使用它以编程方式从测试上下文中查询具体 bean。有没有与 Quarkus 测试类似的方法?我的意思是,我可以将@Injectbean 放入我的测试类中并在@BeforeEach方法中访问它,但我正在寻找一个更“可重用”的解决方案。

非常感谢。

Phi*_* Li 5

geoand让我走上了正确的道路。一种有效的方法是使用QuarkusTestBeforeEachCallback / QuarkusTestMethodContext

因此,鉴于我的自定义 QuarkusTestBeforeEachCallback 实现现在支持通过 CDI 访问 quarkus beans:

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 {
        // ...
    }
}   
Run Code Online (Sandbox Code Playgroud)

和服务声明文件

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

与内容

com.something.test.MyBeforeEachCallback

@QuarkusTest我现在可以在我的测试中使用它,例如:

@QuarkusTest
@DoSomethingBeforeEach
public abstract class AbstractV2Test {

// ...

}
Run Code Online (Sandbox Code Playgroud)

这比我们习惯的 Spring Boot 测试要复杂一些,但它确实有效。