0

I have spring boot tests where I test controllers, services, repositories, and kafka using testcontainers.

I want to have unique topics for each test method. However, I also don't want to create a lot of contexts, I am just fine with having one context and replacing the kafka listener beans with different ones. Is this possible?

This is what my listener looks like:

@Component
class Processor() {
 private val log = LoggerFactory.getLogger(this.javaClass)
 @KafkaListener(
 topics = ["\${topic}"],
 containerFactory = "listenerFactory"
 )
 @Transactional
 fun process(@Payload object: Any, @Header(RECEIVED_KEY) key: String) {
 // some logic here
 }

I tried having a nested @TestConfiguration class inside of the test class and after running all the tests, the number of cached contexts remained the same, however, if I move the nested class outside and put @Import(KafkaTestConfig::class) on the test class, then I see test context cache increase by 1. I'm assuming that the nested approach is what I need, but I want to have unique topic every kafka test method, and what I have achieved is unique topic per test class. How can this be done?

Thanks!

asked May 16, 2025 at 13:14

1 Answer 1

0

It cannot be done with keeping the same application context. The @KafkaListener is parsed when that application context is started. So, that is done for the test scope you declare that application context for.

I wold suffer from test execution performance having dedicated test environment, but same production code, rather than trying to figure out how to abuse bean definition.

The test has to be as minimal and straight forward as possible. And must not interfere to the production code as much as possible.

The goal of integration tests to verify that the whole production code works as close to the production environment as possible.

answered May 16, 2025 at 14:04
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response. However, I'm not sure exactly what you mean. The problem that I have is that sometimes the kafka tests fail, they're flaky, and isolating the test cases from each other by using different topics seems like the way to go.
Consider to use @DirtiesContext to close those application contexts after test suite. This way you won't have active consumer in between test classes.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.