Micronaut MockBean Explained
Published in
2 min readMay 29, 2024
The@MockBean
annotation in the Micronaut framework is used to create replacements for beans in tests. These tests must be annotated with @MicronautTest
. There is often confusion about the roles of the method or field annotated with @MockBean
.
Each method or field specifies both the bean to be replaced and the new bean to be created:
- The bean to be replaced is specified as the value of
@MockBean
and must be the implementation type of the bean, typically it is the one annotated with@Singleton
. - The new bean is specified by the return type of the method or the type of the field.
Creating or replacing a named bean can be more complex:
- The
named
value inside the@MockBean
annotation is used to replace the existing named bean. - The
@Named
annotation is used to name the newly created bean
The most complicated scenario is replacing a bean with a specified qualifier, such as @Primary
, which is particularly challenging:
- Use the
@Replace
annotation directly, specifying the qualifier and/or a factory bean. - Any qualifier added to the method will once again apply to the new bean.