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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

How are you handling the data revolution? We want your take on what's real, what's hype, and what's next in the world of data engineering.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Event-Driven Microservices: How Kafka and RabbitMQ Power Scalable Systems
  • System Coexistence: Bridging Legacy and Modern Architecture
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Why Testing is a Long-Term Investment for Software Engineers

Trending

  • Streamlining DevOps: How Containers and Kubernetes Deliver
  • A Beginner’s Guide to Playwright: End-to-End Testing Made Easy
  • Are Traditional Data Warehouses Being Devoured by Agentic AI?
  • Serverless Machine Learning: Running AI Models Without Managing Infrastructure
  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.

By 
Biju Kunjummen user avatar
Biju Kunjummen
·
Jan. 02, 17 · Opinion
Likes (3)
Comment
Save
Tweet
Share
51.9K 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.

Related

  • Event-Driven Microservices: How Kafka and RabbitMQ Power Scalable Systems
  • System Coexistence: Bridging Legacy and Modern Architecture
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Why Testing is a Long-Term Investment for Software Engineers

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: