gpt4 book ai didi

java - Quarkus BeanManager 与单元测试

转载 作者:行者123 更新时间:2023-12-02 00:57:49 26 4
gpt4 key购买 nike

在上述用例中,BeanManager 在单元测试期间不会返回 bean。该项目是一个Java 库。

Bean接口(interface)

public interface My {
String turn();
}

Bean 限定符

@Qualifier
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface My1 {
}

Bean类

@ApplicationScoped
@My1
public class MyClass1 implements My {
@Override
public String turn() {
return "1";
}
}

以下单元测试失败,bean 列表为空。

@QuarkusTest
public class MyTest {

@Test
public void test1() throws IllegalAccessException, InstantiationException {
Set<Bean<?>> beans = beanManager.getBeans(My.class, new AnnotationLiteral<My1>() {});
MatcherAssert.assertThat(beans.isEmpty(), Is.is(false));
}


@Test
public void test2() throws IllegalAccessException, InstantiationException {
// Class<? extends Annotation>
final Class<? extends Annotation> annotationClass = My1.class;
final Annotation qualifier = new Annotation() {

@Override
public Class<? extends Annotation> annotationType() {
return annotationClass;
}
};
Set<Bean<?>> beans = beanManager.getBeans(My.class, qualifier);
MatcherAssert.assertThat(beans.isEmpty(), Is.is(false));
}

test1 和 test2 的 JUnit 输出

java.lang.AssertionError: 
Expected: is <false>
but: was <true>
Expected :is <false>
Actual :<true>

在另一个 Java 库项目中运行相同的示例效果很好。

在单元测试类中添加注入(inject)的 My 属性也可以正常工作。

可能出了什么问题?在这个例子中 BeanManager 出了什么问题?

谢谢

最佳答案

您的 bean 很可能被视为未使用并在构建期间被删除。请参阅https://quarkus.io/guides/cdi-reference#remove_unused_beans了解更多信息。

您可以尝试使用@Unremovable注释您的bean。

另请注意,BeanManager 并不意味着由应用程序代码使用。这是一个集成 SPI。此外,Quarkus 提供了更惯用的集成第三方库和框架的方法。

关于java - Quarkus BeanManager 与单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61109045/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com