【问题标题】:Quarkus BeanManager with unit test带有单元测试的 Quarkus BeanManager
【发布时间】:2020-04-08 20:00:06
【问题描述】:

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

Bean接口

public interface My {
  String turn();
}

Bean 限定符

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

豆类

@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 库项目中运行相同的示例可以正常工作。

在单元测试类中添加注入的 My 属性也可以。

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

谢谢

【问题讨论】:

    标签: java java-8 cdi quarkus


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-23
      • 2021-06-07
      • 2021-04-30
      • 1970-01-01
      • 2018-09-25
      • 2018-06-03
      • 2019-05-20
      • 1970-01-01
      相关资源
      最近更新 更多