问题
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