我有基于 @QuarkusTest
的测试类。我想实现一个与我的 Quarkus 测试上下文的特定 bean 交互的 JUnit 5 扩展(BeforeEachCallback、AfterEachCallback)。我尝试了 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);
}
然后我可以使用它以编程方式从我的测试上下文中查询具体 bean。有没有类似的方法来进行 Quarkus 测试?我的意思是,我可以将 bean @Inject
放入我的测试类中,并在 @BeforeEach
方法中访问它,但我正在寻找更“可重用”的解决方案。
非常感谢。
最佳答案
geoand让我走上正轨。一个有效的方法是使用 QuarkusTestBeforeEachCallback / QuarkusTestMethodContext .
鉴于我的自定义 QuarkusTestBeforeEachCallback 实现现在支持通过 CDI 访问 quarkus bean:
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 {
// ...
}
}
和一个服务声明文件
src/test/resources/META-INF/services/io.quarkus.test.junit.callback.QuarkusTestBeforeEachCallback
内容
com.something.test.MyBeforeEachCallback
我现在可以在我的 @QuarkusTest
测试中使用它,例如:
@QuarkusTest
@DoSomethingBeforeEach
public abstract class AbstractV2Test {
// ...
}
这比我们习惯的 Spring Boot 测试要复杂一些,但它确实有效。
关于cdi - JUnit5 扩展中的 QuarkusTest 访问 Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72488223/