Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create @MockBean with qualifier by annotating class?

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?

like image 204
maslick Avatar asked Feb 06 '19 07:02

maslick


3 Answers

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
like image 89
Vladislav Kysliy Avatar answered Nov 02 '22 09:11

Vladislav Kysliy


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);
    }
}
like image 5
oberlies Avatar answered Nov 02 '22 09:11

oberlies


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.

like image 4
Sam Brannen Avatar answered Nov 02 '22 09:11

Sam Brannen