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!
1 Answer 1
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.
2 Comments
@DirtiesContext to close those application contexts after test suite. This way you won't have active consumer in between test classes.Explore related questions
See similar questions with these tags.