简体   繁体   中英

Spring @MockBean annotated repository is not used within Kafka listener in test

I have a strange issues. I have a series of test that sometimes use messages on Kafka queue that is received form the listener (all within same distance of the application) and then processed. Kafka is instantiated with the help of Docker.

In the test class is have a repository annotated with @MockBean, and that repository is used also within the Kafka listener.

When is rune the test inside Idea all work and within the listener the repository interface is exalt the mocked bean.

When the tests are executed using Gradle on terminal, sometimes not always, within the lister is used the real repository and not the mocked one.

Thank you for the help.

I have found the problem, seems that the problem was the transaction. In Kafka I use it. Any the digging around an after some search I have found the solution.In tests I create a class for the test configuration that create the mock of the bean as this:

@TestConfiguration
public class ConfMock {
    @Bean
    @Primary
    public IdentityManagementRepository identityManagementRepository() {
        return mock(IdentityManagementRepository.class);
    }

}

and in the real test classes i use the annotation @Import(ConfMock.class)like this:

@Import(ConfMock.class)
@AutoConfigureMockMvc
@SpringBootTest()
@ActiveProfiles("test")
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class ApplicationControllerTest extends AbstractTest {

}

This solution born from this answer , I have bring out the configuration in a separate class, and it work.

Thanks you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM