DZone
Integration Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Integration Zone > Using Kafka With JUnit

Using Kafka With JUnit

The Spring Kafka project provides a way to use Kafka in tests by providing an embedded version of Kafka that is easily set up and torn down.

Biju Kunjummen user avatar by
Biju Kunjummen
·
Jan. 02, 17 · Integration Zone · Opinion
Like (3)
Save
Tweet
50.12K Views

Join the DZone community and get the full member experience.

Join For Free

One of the neat features that the Spring Kafka project provides, apart from an easier-to-use abstraction over raw Kafka Producer and Consumer, is a way to use Kafka in tests. It does this by providing an embedded version of Kafka that can be set up and torn down very easily. 

All that a project needs in order to include this support is the spring-kafka-test module for a Gradle build in the following way (as seen here): 

1testCompile "org.springframework.kafka:spring-kafka-test:1.1.2.BUILD-SNAPSHOT"          

(Note that I am using a snapshot version of the project as this has support for Kafka 0.10+.)

With this dependency in place, an embedded Kafka can be spun up in a test using the @ClassRule of JUnit:

@ClassRule public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(
  2, true, 2, "messages");

This would start up a Kafka Cluster with two brokers with a topic called "messages" using two partitions. The class rule would make sure that a Kafka cluster is spun up before the tests are run and then shut down at the end of it.

Here is how a sample how it looks with a raw Kafka producer and consumer using an embedded Kafka cluster. The embedded Kafka can be used for retrieving the properties required by the Kafka producer and consumer:

Map<String, Object> senderProps = KafkaTestUtils.producerProps(embeddedKafka);
KafkaProducer<Integer, String> producer = newKafkaProducer<>(senderProps);
producer.send(newProducerRecord<>("messages", 0, 0, "message0")).get();
producer.send(newProducerRecord<>("messages", 0, 1, "message1")).get();
producer.send(newProducerRecord<>("messages", 1, 2, "message2")).get();
producer.send(newProducerRecord<>("messages", 1, 3, "message3")).get();     
Map<String, Object> consumerProps =
  KafkaTestUtils.consumerProps("sampleRawConsumer", "false", embeddedKafka);
consumerProps.put("auto.offset.reset", "earliest");   
finalCountDownLatch latch = newCountDownLatch(4);
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() -> {    
  KafkaConsumer<Integer, String> kafkaConsumer = newKafkaConsumer<>(consumerProps);
  kafkaConsumer.subscribe(Collections.singletonList("messages"));    
  try{       
    while(true) {            
    ConsumerRecords<Integer, String> records = kafkaConsumer.poll(100);            for(ConsumerRecord<Integer, String> record : records) {                LOGGER.info("consuming from topic = {}, partition = {}, offset = {}, key = {}, value = {}",                        record.topic(), record.partition(), record.offset(), record.key(), record.value());                latch.countDown();            }        }    } finally{        kafkaConsumer.close();    }});                
assertThat(latch.await(90, TimeUnit.SECONDS)).isTrue();

A little more comprehensive test is available here.

kafka JUnit

Published at DZone with permission of Biju Kunjummen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What Is Pair Programming?
  • Building a QR Code Generator with Azure Functions
  • Chopping the Monolith: The Demo
  • Vaadin Apps as Native Executables Using Quarkus Native

Comments

Integration Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo