此内容没有您所选择的语言版本。
Chapter 6. Mocking CDI beans
Quarkus allows you to mock certain CDI beans for specific tests.
You can mock an object using one of the following methods:
-
Override the bean you that you want to mock with a class in the
src/test/javadirectory, and put the@Alternativeand@Priority(1)annotations on the bean. -
Use the
io.quarkus.test.Mockstereotype annotation. The@Mockannotation contains the@Alternative,@Priority(1)and@Dependentannotations.
The following procedure shows how to mock an external service using the @Alternative annotation.
Procedure
Create the
ExternalServicein thesrc/main/javadirectory similar to the following example:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create a class
UsesExternalServicethat usesExternalServicein thesrc/main/javadirectory:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create a test in the
src/test/javadirectory similar to the following example:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create the
MockExternalServicein thesrc/test/javathat uses the@Alternativeannotation:Copy to Clipboard Copied! Toggle word wrap Toggle overflow - 1
- The
MockExternalServiceis injected wherever theExternalServiceis being used. In this example,MockExternalServicewill be used inUsesExternalService.
NoteYou can use the
@Mockannotation instead of the@Alternative,@Priority(1)and@Dependentannotations.The following example shows how to create
MockExternalServiceclass that uses the@Mockannotation:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Change the asserted string from
"external"to"mock"in the test:Copy to Clipboard Copied! Toggle word wrap Toggle overflow