DZone
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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Big Data
  4. 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 · Opinion
Like (3)
Save
Tweet
Share
50.75K 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

  • A Brief Overview of the Spring Cloud Framework
  • Top 5 Node.js REST API Frameworks
  • How to Check Docker Images for Vulnerabilities
  • OpenID Connect Flows

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • 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: