Reset kafka testcontainers without clearing and recreating the testcontainer after every junit test

Viewed 432

I am using kafka testcontainers with JUnit5. Can someone let me know how can I delete data from Kafka testcontainers after each test so that I don't have to destroy and recreate the kafka testcontainer every time.

  • Test Container Version - 1.6.2
  • Docker Kafka Image Name - confluentinc/cp-kafka:5.2.1
1 Answers

Make the container variable static

Containers declared as static fields will be shared between test methods. They will be started only once before any test method is executed and stopped after the last test method has executed

https://www.testcontainers.org/test_framework_integration/junit_5/

Make sure that you don't share state between tests, though. For example, if you want to test creating a topic, producing to it, then consuming from it, and deleting it, those all should be in one test. Although you can call separate non test methods.

That being said, each test should ideally use a unique topic name. One that describes the test, maybe.

Also, as documented, you cannot use the parallel test runner

Related