Class KafkaClusterExtension

java.lang.Object
io.kroxylicious.testing.kafka.junit5ext.KafkaClusterExtension
All Implemented Interfaces:
BeforeAllCallback, BeforeEachCallback, Extension, ParameterResolver, TestTemplateInvocationContextProvider

A JUnit 5 extension that allows declarative injection of a KafkaCluster into a test via static or instance field(s) and/or parameters.

A simple example looks like:


 import io.kroxylicious.junit5.KafkaClusterExtension;
 import org.apache.kafka.clients.producer.Producer;
 import org.apache.kafka.clients.producer.ProducerRecord;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.ExtendWith;

 @ExtendWith(KafkaClusterExtension.class) // <1>
 class MyTest {

     KafkaCluster cluster; // <2>

     @Test
     public void testProducer(
                 Producer<String, String> producer // <3>
             ) throws Exception {
         producer.send(new ProducerRecord<>("hello", "world")).get();
     }
 }
 

Notes:

  1. You have to tell Junit that you're using the extension using @ExtendWith.
  2. An instance field of type KafkaCluster will cause a new cluster to be provisioned for each test in the class. Alternatively you can use a parameter on a @Test-annotated method. If you use a static field then a single cluster will be provisioned for all the tests in the class.
  3. Your test methods can declare Producer, Consumer and Admin-typed parameters. They will be configured to bootstrap against the cluster.

Injection rules

The extension supports injecting clusters and clients:

  • into fields of the test class
  • as parameters to @BeforeAll
  • as parameters to @BeforeEach
  • as parameters to test methods
To avoid collisions with other extensions, such as Mockito, we will only inject into fields which:
  • have no annotations
  • OR are annotated with annotations from the following packages
  • java.lang
  • org.junit
  • io.kroxylicious