How can I override a CDI bean in Quarkus for testing?

人走茶凉 提交于 2021-02-10 19:10:54

问题


I have a CDI bean like so:

@Dependent
class Parser {

  String[] parse(String expression) {
     return expression.split("::");
  }
}

It gets injected into another bean like this:

@ApplicationScoped
class ParserService {

  @Inject
  Parser parser;

  //...
}

What I want to do is continue to use Parser in my regular code, but I want to use a "mock" for testing purposes. How can I achieve that?


回答1:


All that needs to be done in this case is to create bean in test directory that looks something like the following:

@Alternative
@Priority(1)
@Singleton
class MockParser extends Parser {

    String[] parse(String expression) {
        // some other implementation
    }
}

Here @Alternative and @Priority are CDI annotations that Quarkus will use to determine that MockParser will be used instead of Parser (for tests only of course).

More details can be found in the extension author's guide.

Note: The use of @Alternarive and @Priority is not of course limited to test code only. They can be used in any situation that use "overriding" a bean.



来源:https://stackoverflow.com/questions/56119064/how-can-i-override-a-cdi-bean-in-quarkus-for-testing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!