问题描述
我有一个像这样的 CDI bean:
I have a CDI bean like so:
@Dependent
class Parser {
String[] parse(String expression) {
return expression.split("::");
}
}
它像这样被注入到另一个 bean 中:
It gets injected into another bean like this:
@ApplicationScoped
class ParserService {
@Inject
Parser 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?
推荐答案
在这种情况下需要做的就是在 test 目录中创建如下所示的 bean:
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
}
}
这里的@Alternative
和@Priority
是CDI 注释,Quarkus 将使用它们来确定将使用MockParser
而不是Parser
(当然仅用于测试).
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.
注意:@Alternarive
和 @Priority
的使用当然不仅限于测试代码.它们可以用于任何使用覆盖"bean 的情况.
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.
这篇关于如何在 Quarkus 中覆盖 CDI bean 进行测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!