Search code examples
javaspring-bootintegration-testingspring-bean

Spring Boot Integration test mock external dependency


I'm trying to create integration tests for my Spring Boot app. The idea is to launch an embedded postgres db and run http calls with TestRestTemplate to my controllers.

The problem is my project has a dependency we use for redis queues.

    <dependency>
      <groupId>com.github.sonus21</groupId>
      <artifactId>rqueue-spring-boot-starter</artifactId>
      <version>2.9.0-RELEASE</version>
    </dependency>

I've tried to mock out the dependencies and most of them work, but with this one it complains I guess because it is a @Configuration not a @Component:

Dependency config class:

@Configuration
@AutoConfigureAfter({RedisAutoConfiguration.class})
@ComponentScan({"com.github.sonus21.rqueue.web", "com.github.sonus21.rqueue.dao"})
public class RqueueListenerAutoConfig extends RqueueListenerBaseConfig {
    public RqueueListenerAutoConfig() {
    }
...
}

My test config class

@TestConfiguration
public class TestRestTemplateConfig {

    @Bean
    @Primary
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public RqueueListenerAutoConfig rqueueListenerAutoConfig() {
        return Mockito.mock(RqueueListenerAutoConfig.class);
    }

    ....
}

I've tried with @AutoConfigureOrder(1) at my config class but the original RqueueListenerAutoConfig launches before anything and my mocked beans haven't been declared yet.

To be honest mocking every service on that dependency is a pain, but I haven't figured out a way to mock the whole dependency with a single configuration. I tried not loading the dependency when I'm on the test profile but since it runs spring context my code needs it.

My test class has the following config:

@SpringBootTest
@Import(TestRestTemplateConfig.class)
@ActiveProfiles("test")
public class TestClass {
...
}

Any clues?

Thanks.


Solution

  • Try

    @EnableAutoConfiguration(exclude=RqueueListenerAutoConfig.class)