In my Spring Boot test I'm using 2 mock beans with different qualifiers:
@RunWith(SpringRunner.class)
@SpringBootTest
class HohoTest {
@MockBean @Qualifier("haha") IHaha ahaha;
@MockBean @Qualifier("hoho") IHaha ohoho;
}
Since I'm not using these beans explicitly, I would rather move them away from the class body, as the @MockBean
annotation is now repeatable:
@RunWith(SpringRunner.class)
@SpringBootTest
@MockBean(IHaha.class)
@MockBean(IHaha.class)
class HohoTest {}
However, I need to pass in a qualifier as well, since they have the same type. Any idea on how I can achieve that?
Because using annotation @Qualifier
means choose bean by name, so you can set up a name for a mock with code like this:
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {JsonMapperConfig.class})
public class IntegrationFlowTest {
@MockBean(name = "s3MessageRepository")
private S3Repository s3MessageRepository;
// etc
If it is okay to move the mock definition completely out of the test class, you could also create the mocks in a separate @Configuration
class:
@Configuration
public class MockConfiguration
{
@Bean @Qualifier("haha")
public IHaha ahaha() {
return Mockito.mock(IHaha.class);
}
@Bean @Qualifier("hoho")
public IHaha ohoho() {
return Mockito.mock(IHaha.class);
}
}
When declaring @MockBean
at the class level, there is currently no support for providing a qualifier.
If you would like to have such support, I suggest you request it in the Spring Boot issue tracker.
Otherwise, you will need to continue declaring @MockBean
on fields alongside @Qualifier
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With