javaspringspring-bootspring-kafkaspring-boot-test

Kafka Consumer test works with SpringBootTest but not with ContextConfiguration


From my understanding of the @SpringBootTest configuration based on the docs, if the classes parameter is specified, it is equivalent with a @ContextConfiguration with the same parameter:

The component classes to use for loading an ApplicationContext. Can also be specified using @ContextConfiguration(classes=...). If no explicit classes are defined the test will look for nested @Configuration classes, before falling back to a @SpringBootConfiguration search.

However, I am trying to write a test for my @KafkaListener, and it works with @SpringBootTest, but not with @ContextConfiguration. So the working configuration is

@SpringBootTest(classes = KafkaTestContextConfiguration.class)
@ContextConfiguration(initializers = TestContainersInitializer.class)
@TestPropertySource(locations = "classpath:springProperties/application.properties")
@ExtendWith(SpringExtension.class)

while the theoretically equivalent

@ContextConfiguration(initializers = TestContainersInitializer.class)
@TestPropertySource(classes = KafkaTestContextConfiguration.class, locations = "classpath:springProperties/application.properties")
@ExtendWith(SpringExtension.class)

does not work (it cannot consume the Kafka messages probably because the listener is not correctly autowired). Is @SpringBootTest doing something @ContextConfiguration is missing in this context?


Solution

  • Correct, the @SpringBootTest also does an auto-configuration, which includes @EnableKafka. See its Javadocs:

     * <li>Automatically searches for a
     * {@link SpringBootConfiguration @SpringBootConfiguration} when nested
     * {@code @Configuration} is not used, and no explicit {@link #classes() classes} are
     * specified.</li>
    

    So, if you don't want the whole auto-configuration, but just restricted to Spring Kafka stuff, you can @Import(KafkaAutoConfiguration.class) on your KafkaTestContextConfiguration.