I have spring application with some embedded kafka tests @EmbeddedKafka. For each test I need a separate topic.
@ExtendWith(SpringExtension::class)
@SpringBootTest(
classes = [
Application::class
]
)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@EmbeddedKafka(
partitions = 1,
topics = [
"topicName"
]
)
@ActiveProfiles("test")
@Import(value = [ApplicationListenerCaseTest.TestConfig::class])
class ApplicationListenerCaseTest {
@Autowired
private lateinit var testKafkaTemplate: KafkaTemplate<String, String>
@Autowired
private lateinit var kafkaListenerEndpointRegistry: KafkaListenerEndpointRegistry
@Autowired
private lateinit var kafkaEmbeddedKafka: EmbeddedKafkaBroker
override fun getTestKafkaTemplate() = testKafkaTemplate
@BeforeEach
fun setup() {
for (msgListenerContainer in kafkaListenerEndpointRegistry.listenerContainers) {
ContainerTestUtils.waitForAssignment(msgListenerContainer, kafkaEmbeddedKafka.partitionsPerTopic)
}
}
@Test
fun test() {
// ...
}
@TestConfiguration
class TestConfig {
@Bean
@Primary
fun testKafkaTemplate(
@Value("topicName") topic: String,
broker: EmbeddedKafkaBroker
) = KafkaTemplate(DefaultKafkaProducerFactory<String, String>(KafkaTestUtils.producerProps(broker)))
.apply { defaultTopic = topic }
}
}
There are several such tests and they take a very long time.I think the long execution is due to the fact that a separate kafka broker is created for each test.
Is there a way to run all tests in one broker and to avoid wasting time creating a new context for every test?