Este contenido no está disponible en el idioma seleccionado.
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/java
directory, and put the@Alternative
and@Priority(1)
annotations on the bean. -
Use the
io.quarkus.test.Mock
stereotype annotation. The@Mock
annotation contains the@Alternative
,@Priority(1)
and@Dependent
annotations.
The following procedure shows how to mock an external service using the @Alternative
annotation.
Procedure
Create the
ExternalService
in thesrc/main/java
directory similar to the following example:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create a class
UsesExternalService
that usesExternalService
in thesrc/main/java
directory:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create a test in the
src/test/java
directory similar to the following example:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create the
MockExternalService
in thesrc/test/java
that uses the@Alternative
annotation:Copy to Clipboard Copied! Toggle word wrap Toggle overflow - 1
- The
MockExternalService
is injected wherever theExternalService
is being used. In this example,MockExternalService
will be used inUsesExternalService
.
NoteYou can use the
@Mock
annotation instead of the@Alternative
,@Priority(1)
and@Dependent
annotations.The following example shows how to create
MockExternalService
class that uses the@Mock
annotation: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