SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Downloaden Sie, um offline zu lesen
Markus Günther
Freelance Software Engineer / Architect
mail@mguenther.net | mguenther.net | @markus_guenther
Apache Kafka
Testing Kafka-enabled software components
2
There are several approaches to testing Kafka-enabled
components or services.
Problem
Solution ▪ Spring Kafka provides an embeddable cluster
▪ Lacks the possiblity to work with external clusters
▪ Leads to boilerplate code in your test
▪ There are (costly) testing tools that are able to inject records into topics
▪ Lacks the possibility to work with embedded clusters
▪ Suitable for system testing, not integration testing
▪ Testing Kafka-based components or services is not trivial
▪ Need to have a working cluster
▪ Must be able to instrument the cluster
▪ Mocking is not an option for integration or system tests
3
Kafka for JUnit is suitable for integration testing as well as
system testing.
Solution ▪ Kafka for JUnit
▪ Works with embedded Kafka clusters – suitable for integration testing
▪ Works with external Kafka clusters – suitable for system testing
▪ Features a concise and readable API
▪ Features fault injection to trigger error handling
▪ Integrates well with Spring Kafka
4
Kafka for JUnit allows you to write integration tests that work
against an embedded Kafka cluster.
Integration Test
JUNIT JUPITER
Consumer / Producer
KAFKA-BASED COMPONENT
my.test.topic
EMBEDDED APACHE KAFKA CLUSTER
VERTICALS
instruments
provisions
interacts
with
6
Kafka for JUnit allows you to write system tests that work against
an external Kafka cluster.
VERTICALS
Event Producer
SERVICE A
Event Consumer
SERVICE B
topic.for.events
APACHE KAFKA CLUSTER
System Test
JUNIT JUPITER
trigger use case
observes
topic
for
expected
records
publishes
events
consumes
events
7
Kafka for JUnit provides abstractions for interacting with a Kafka cluster
through EmbeddedKafkaCluster and ExternalKafkaCluster.
my.test.topic
APACHE KAFKA CLUSTER
RecordProducer
EmbeddedKafkaCluster
RecordConsumer
TopicManager
FaultInjection
my.test.topic
APACHE KAFKA CLUSTER
RecordProducer
ExternalKafkaCluster
RecordConsumer
TopicManager
8
A RecordProducer provides the means to send key-value pairs
or non-keyed values to a Kafka topic.
public interface RecordProducer {
<V> List<RecordMetadata> send(SendValues<V> sendRequest) throws ...;
<V> List<RecordMetadata> send(SendValuesTransactional<V> sendRequest) throws ...;
<K,V> List<RecordMetadata> send(SendKeyValues<K,V> sendRequest) throws ...;
<K,V> List<RecordMetadata> send(SendKeyValuesTransactional<K,V> sendRequest) ...;
/* overloaded methods that accept builder instances
* for the resp. type have been omitted for brevity
*/
}
Kafka for JUnit provides builders
for these requests!
Interface definition of RecordProducer
9
Publishing data to a Kafka topic is as simple as contributing a
one-liner in the default case.
kafka.send(SendValues.to(“my.test.topic“, “a“, “b“, “c“));
Sending non-keyed values using defaults
kafka.send(SendValuesTransactional.inTransaction(
“my.test.topic“,
Arrays.asList(“a“, “b“, “c“)));
kafka.send(SendValues.to(“my.test.topic“, “a“, “b“, “c“))
.with(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, “true“)
.with(ProducerConfig.MAX_IN_FLIGHT_REQUEST_PER_CONNECTION, “1“));
Sending non-keyed values using overrides
Sending non-keyed values transactionally
1
A RecordConsumer provides the means to read data from a topic or
observe a topic until some criteria is met or a timeout elapses.
public interface RecordConsumer {
<V> List<V> readValues(ReadKeyValues<String,V> readRequest) throws ...;
<K,V> List<KeyValue<K,V>> read(ReadKeyValues<K,V> readRequest) throws ...;
<V> List<V> observeValues(ObserveKeyValues<String,V> observeRequest) throws ...;
<K,V> List<KeyValue<K,V>> observe(ObserveKeyValues<K,V> observeRequest) throws ...;
/* overloaded methods that accept builder instances
* for the resp. type have been omitted for brevity
*/
}
Kafka for JUnit provides builders
for these requests!
Interface definition of RecordConsumer
1
Consuming records is just as easy as producing them.
val values = kafka.readValues(ReadKeyValues.from(“my.test.topic“));
Consuming only values using defaults
List<KeyValue<String, Long>> records = kafka.read(ReadKeyValues
.from(“my.test.topic“, Long.class)
.with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ...));
val records = kafka.read(ReadKeyValues.from(“my.test.topic“));
Consuming key-value pairs using defaults
Consuming key-value pairs using overrides
1
Observations can be used to let a test fail unless given criteria
are met.
kafka.observeValues(ObserveKeyValues.on(“my.test.topic“, 3));
Observing a topic until n values have been consumed
val keyFilter = Integer.parseInt(k) % 2 == 0;
kafka.observe(ObserveKeyValues.on(“my.test.topic“, 3, Integer.class)
.with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ...)
.filterOnKeys(keyFilter));
List<KeyValue<String,String>> observedRecords = kafka
.observe(ObserveKeyValues.on(“my.test.topic“, 3));
Observing a topic until n records have been consumed
Using filters when consuming or observing a topic
1
A TopicManager provides the means to manage Kafka
topics.
public interface TopicManager {
void createTopic(TopicConfig config);
void deleteTopic(String topic);
boolean exists(String topic);
Map<Integer, LeaderAndIsr> fetchLeaderAndIsr(String topic);
Properties fetchTopicConfig(String topic);
/* overloaded methods that accept builder instances for the resp. type have been
omitted for brevity */
}
Kafka for JUnit provides builders
for these requests!
Interface definition of TopicManager
1
The default TopicManager implementation leverages the
AdminClient implementation of the Kafka Client library.
kafka.createTopic(TopicConfig.withName(“my.test.topic“));
Creating a topic using defaults
kafka.deleteTopic(“my.test.topic“);
Deleting a topic
kafka.createTopic(TopicConfig.withName(“my.test.topic“)
.withNumberOfPartitions(5)
.withNumberOfReplicas(1));
Creating a topic with specific properties
1
Writing integration tests with
Kafka for JUnit
1
Let’s write a test that exercises the write-path of Kafka-based
component.
TurbineEventPublisherTest
JUNIT JUPITER
TurbineEventPublisher
TURBINE REGISTRY
turbine.lifecycle.events
EMBEDDED APACHE KAFKA CLUSTER
instruments
provisions
interacts
with
1
1
Let’s write a simple test that verifies that TurbineEventPublisher
is able to write events to the designated topic.
public class TurbineEventPublisherTest {
private EmbeddedKafkaCluster kafka;
@BeforeEach
void setupKafka() {
kafka = provisionWith(defaultClusterConfig());
kafka.start();
}
@AfterEach
void tearDownKafka() {
kafka.stop();
}
}
Provide the skeleton for the component test incl. a workable Kafka cluster.
static import from
ExternalKafkaCluster
static import from
ExternalKafkaClusterConfig
1
The observe method throws an AssertionError once a
certain configurable amount of time has elapsed.
var config = Map.<String, Object>of(
ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBrokerList());
var publisher = new TurbineEventPublisher(“turbine.lifecycle.events“,
config);
var event = new TurbineRegisteredEvent(“1a5c6012“, 49.875114, 8.978702);
publisher.log(event);
Create an instance of the subject-under-test and publish test data
2
The observe method throws an AssertionError once a
certain configurable amount of time has elapsed. (cont.)
kafka.observe(ObserveKeyValues
.on(“turbine.lifecycle.events“, 1, TurbineEvent.class)
.observeFor(15, TimeUnit.SECONDS)
.filterOnKeys(key -> key.equals(“1a5c6012“))
.with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
TurbineEventDeserializer.class));
Observe the designated topic for new data
override arbitrary
consumer properties
the topic we want to
observe
the number of
records we expect
the value type of the
expected records
use filters to add
observation criterias
2
The observe method returns all records that it obtained from
watching the topic.
var record = kafka.observe(
on(“turbine.lifecycle.events“, 1, TurbineEvent.class)
.with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
TurbineEventDeserializer.class))
.stream()
.findFirst()
.orElseThrow(AssertionError::new);
assertThat(record.getKey()).isEqualTo(“1a5c6012“);
assertThat(record.getValue()).isInstanceOf(TurbineRegisteredEvent.class);
Fetch observed records and assert that their data is what you expect it to be
2
Writing systems tests with
Kafka for JUnit
2
2
We’ll use a simple client interface to provide the means to exert an
external stimulus on the system. (cont.)
Listing 1: Example for Feign-based HTTP client that interacts with the system
public interface GettingThingsDone {
@RequestLine(“POST /items“)
@Headers(“Content-Type: application/json“)
Response createItem(CreateItem payload);
@RequestLine(“GET /items/{itemId}“)
@Headers(“Accept: application/json“)
Item getItem(@Param(“itemId“) String itemId);
/* additional methods omitted for brevity */
}
Example for Feign-based HTTP client that interacts with the system
2
We’ll use a simple client interface to provide the means to exert an
external stimulus on the system. (cont.)
Listing 1: Example for Feign-based HTTP client that interacts with the system
val kafka = ExternalKafkaCluster.at(“http://localhost:9092“);
Gain programmatic access to the cluster
val itemId = extractItemId(response);
Extract the ID of the newly created item from the response
val gtd = createGettingThingsDoneClient();
val payload = new CreateItem(“Buy groceries!“);
val response = gtd.createItem(payload)
Trigger a use case using the client interface
2
Leverage Kafka for JUnit to observe the designated topic and apply
assertions on the returned records.
Listing 1: Example for Feign-based HTTP client that interacts with the system
List<AvroItemEvent> publishedEvents = kafka
.observeValues(on(“item.events“, 1, AvroItemEvent.class)
.observeFor(10, TimeUnit.SECONDS)
.with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
ItemEventDeserializer.class)
.filterOnKeys(aggregateId -> aggregateId.equals(itemId)));
Observe the designated topic for the
throws an AssertionError
if the timeout elapses
2
Want to know more?
GitHub
Blog ▪ Günther, M., Writing component tests for Kafka producers,
https://bit.ly/39NpoCU
▪ Günther, M., Writing component tests for Kafka consumers,
https://bit.ly/36KrXoV
▪ Günther, M., Writing system tests for a Kafka-enabled microservice,
https://bit.ly/2OUeEMs
▪ Günther, M., Using Kafka for JUnit with Spring Kafka,
https://bit.ly/3c61WSx
▪ Kafka for JUnit on GitHub,
https://mguenther.github.io/kafka-junit/
▪ User Guide to Kafka for JUnit,
https://mguenther.github.io/kafka-junit/
2
Questions?
mguenther.net markus_guenther
mail@mguenther.net

Weitere ähnliche Inhalte

Was ist angesagt?

Microservices, Containers, Kubernetes, Kafka, Kanban
Microservices, Containers, Kubernetes, Kafka, KanbanMicroservices, Containers, Kubernetes, Kafka, Kanban
Microservices, Containers, Kubernetes, Kafka, KanbanAraf Karsh Hamid
 
What Is Kubernetes | Kubernetes Introduction | Kubernetes Tutorial For Beginn...
What Is Kubernetes | Kubernetes Introduction | Kubernetes Tutorial For Beginn...What Is Kubernetes | Kubernetes Introduction | Kubernetes Tutorial For Beginn...
What Is Kubernetes | Kubernetes Introduction | Kubernetes Tutorial For Beginn...Edureka!
 
Introduction to Kafka Streams
Introduction to Kafka StreamsIntroduction to Kafka Streams
Introduction to Kafka StreamsGuozhang Wang
 
Introduction to Resilience4j
Introduction to Resilience4jIntroduction to Resilience4j
Introduction to Resilience4jKnoldus Inc.
 
Schema Registry 101 with Bill Bejeck | Kafka Summit London 2022
Schema Registry 101 with Bill Bejeck | Kafka Summit London 2022Schema Registry 101 with Bill Bejeck | Kafka Summit London 2022
Schema Registry 101 with Bill Bejeck | Kafka Summit London 2022HostedbyConfluent
 
카프카(kafka) 성능 테스트 환경 구축 (JMeter, ELK)
카프카(kafka) 성능 테스트 환경 구축 (JMeter, ELK)카프카(kafka) 성능 테스트 환경 구축 (JMeter, ELK)
카프카(kafka) 성능 테스트 환경 구축 (JMeter, ELK)Hyunmin Lee
 
Kubernetes
KubernetesKubernetes
Kuberneteserialc_w
 
Fundamentals of Apache Kafka
Fundamentals of Apache KafkaFundamentals of Apache Kafka
Fundamentals of Apache KafkaChhavi Parasher
 
카프카 기반의 대규모 모니터링 플랫폼 개발이야기
카프카 기반의 대규모 모니터링 플랫폼 개발이야기카프카 기반의 대규모 모니터링 플랫폼 개발이야기
카프카 기반의 대규모 모니터링 플랫폼 개발이야기if kakao
 
Resilience4j with Spring Boot
Resilience4j with Spring BootResilience4j with Spring Boot
Resilience4j with Spring BootKnoldus Inc.
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Lars Thorup
 
Introduction to Microservices Patterns
Introduction to Microservices PatternsIntroduction to Microservices Patterns
Introduction to Microservices PatternsDimosthenis Botsaris
 
Testing Kafka - The Developer Perspective
Testing Kafka - The Developer PerspectiveTesting Kafka - The Developer Perspective
Testing Kafka - The Developer Perspectivemaiktoepfer
 
How is Kafka so Fast?
How is Kafka so Fast?How is Kafka so Fast?
How is Kafka so Fast?Ricardo Paiva
 
Kafka Streams: What it is, and how to use it?
Kafka Streams: What it is, and how to use it?Kafka Streams: What it is, and how to use it?
Kafka Streams: What it is, and how to use it?confluent
 
Event Sourcing & CQRS, Kafka, Rabbit MQ
Event Sourcing & CQRS, Kafka, Rabbit MQEvent Sourcing & CQRS, Kafka, Rabbit MQ
Event Sourcing & CQRS, Kafka, Rabbit MQAraf Karsh Hamid
 
Tuning Apache Kafka Connectors for Flink.pptx
Tuning Apache Kafka Connectors for Flink.pptxTuning Apache Kafka Connectors for Flink.pptx
Tuning Apache Kafka Connectors for Flink.pptxFlink Forward
 
InfluxDB Roadmap: What’s New and What’s Coming
InfluxDB Roadmap: What’s New and What’s ComingInfluxDB Roadmap: What’s New and What’s Coming
InfluxDB Roadmap: What’s New and What’s ComingInfluxData
 
Spring Boot+Kafka: the New Enterprise Platform
Spring Boot+Kafka: the New Enterprise PlatformSpring Boot+Kafka: the New Enterprise Platform
Spring Boot+Kafka: the New Enterprise PlatformVMware Tanzu
 

Was ist angesagt? (20)

Microservices, Containers, Kubernetes, Kafka, Kanban
Microservices, Containers, Kubernetes, Kafka, KanbanMicroservices, Containers, Kubernetes, Kafka, Kanban
Microservices, Containers, Kubernetes, Kafka, Kanban
 
What Is Kubernetes | Kubernetes Introduction | Kubernetes Tutorial For Beginn...
What Is Kubernetes | Kubernetes Introduction | Kubernetes Tutorial For Beginn...What Is Kubernetes | Kubernetes Introduction | Kubernetes Tutorial For Beginn...
What Is Kubernetes | Kubernetes Introduction | Kubernetes Tutorial For Beginn...
 
Introduction to Kafka Streams
Introduction to Kafka StreamsIntroduction to Kafka Streams
Introduction to Kafka Streams
 
Introduction to Resilience4j
Introduction to Resilience4jIntroduction to Resilience4j
Introduction to Resilience4j
 
Schema Registry 101 with Bill Bejeck | Kafka Summit London 2022
Schema Registry 101 with Bill Bejeck | Kafka Summit London 2022Schema Registry 101 with Bill Bejeck | Kafka Summit London 2022
Schema Registry 101 with Bill Bejeck | Kafka Summit London 2022
 
카프카(kafka) 성능 테스트 환경 구축 (JMeter, ELK)
카프카(kafka) 성능 테스트 환경 구축 (JMeter, ELK)카프카(kafka) 성능 테스트 환경 구축 (JMeter, ELK)
카프카(kafka) 성능 테스트 환경 구축 (JMeter, ELK)
 
Kubernetes
KubernetesKubernetes
Kubernetes
 
Fundamentals of Apache Kafka
Fundamentals of Apache KafkaFundamentals of Apache Kafka
Fundamentals of Apache Kafka
 
카프카 기반의 대규모 모니터링 플랫폼 개발이야기
카프카 기반의 대규모 모니터링 플랫폼 개발이야기카프카 기반의 대규모 모니터링 플랫폼 개발이야기
카프카 기반의 대규모 모니터링 플랫폼 개발이야기
 
Resilience4j with Spring Boot
Resilience4j with Spring BootResilience4j with Spring Boot
Resilience4j with Spring Boot
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)
 
Introduction to Microservices Patterns
Introduction to Microservices PatternsIntroduction to Microservices Patterns
Introduction to Microservices Patterns
 
Testing Kafka - The Developer Perspective
Testing Kafka - The Developer PerspectiveTesting Kafka - The Developer Perspective
Testing Kafka - The Developer Perspective
 
How is Kafka so Fast?
How is Kafka so Fast?How is Kafka so Fast?
How is Kafka so Fast?
 
Kafka Streams: What it is, and how to use it?
Kafka Streams: What it is, and how to use it?Kafka Streams: What it is, and how to use it?
Kafka Streams: What it is, and how to use it?
 
Event Sourcing & CQRS, Kafka, Rabbit MQ
Event Sourcing & CQRS, Kafka, Rabbit MQEvent Sourcing & CQRS, Kafka, Rabbit MQ
Event Sourcing & CQRS, Kafka, Rabbit MQ
 
Tuning Apache Kafka Connectors for Flink.pptx
Tuning Apache Kafka Connectors for Flink.pptxTuning Apache Kafka Connectors for Flink.pptx
Tuning Apache Kafka Connectors for Flink.pptx
 
InfluxDB Roadmap: What’s New and What’s Coming
InfluxDB Roadmap: What’s New and What’s ComingInfluxDB Roadmap: What’s New and What’s Coming
InfluxDB Roadmap: What’s New and What’s Coming
 
Spring Boot+Kafka: the New Enterprise Platform
Spring Boot+Kafka: the New Enterprise PlatformSpring Boot+Kafka: the New Enterprise Platform
Spring Boot+Kafka: the New Enterprise Platform
 
Envoy and Kafka
Envoy and KafkaEnvoy and Kafka
Envoy and Kafka
 

Ähnlich wie Testing Kafka components with Kafka for JUnit

Exactly-once Stream Processing with Kafka Streams
Exactly-once Stream Processing with Kafka StreamsExactly-once Stream Processing with Kafka Streams
Exactly-once Stream Processing with Kafka StreamsGuozhang Wang
 
Kafka Summit SF 2017 - Exactly-once Stream Processing with Kafka Streams
Kafka Summit SF 2017 - Exactly-once Stream Processing with Kafka StreamsKafka Summit SF 2017 - Exactly-once Stream Processing with Kafka Streams
Kafka Summit SF 2017 - Exactly-once Stream Processing with Kafka Streamsconfluent
 
Spark Streaming Info
Spark Streaming InfoSpark Streaming Info
Spark Streaming InfoDoug Chang
 
Exactly-once Data Processing with Kafka Streams - July 27, 2017
Exactly-once Data Processing with Kafka Streams - July 27, 2017Exactly-once Data Processing with Kafka Streams - July 27, 2017
Exactly-once Data Processing with Kafka Streams - July 27, 2017confluent
 
How Scala promotes TDD
How Scala promotes TDDHow Scala promotes TDD
How Scala promotes TDDShai Yallin
 
Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...
Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...
Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...HostedbyConfluent
 
Kubernetes fundamentals
Kubernetes fundamentalsKubernetes fundamentals
Kubernetes fundamentalsVictor Morales
 
I can't believe it's not a queue: Kafka and Spring
I can't believe it's not a queue: Kafka and SpringI can't believe it's not a queue: Kafka and Spring
I can't believe it's not a queue: Kafka and SpringJoe Kutner
 
Secure Kafka at scale in true multi-tenant environment ( Vishnu Balusu & Asho...
Secure Kafka at scale in true multi-tenant environment ( Vishnu Balusu & Asho...Secure Kafka at scale in true multi-tenant environment ( Vishnu Balusu & Asho...
Secure Kafka at scale in true multi-tenant environment ( Vishnu Balusu & Asho...confluent
 
Declarative benchmarking of cassandra and it's data models
Declarative benchmarking of cassandra and it's data modelsDeclarative benchmarking of cassandra and it's data models
Declarative benchmarking of cassandra and it's data modelsMonal Daxini
 
TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...
TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...
TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...tdc-globalcode
 
How to Build an Apache Kafka® Connector
How to Build an Apache Kafka® ConnectorHow to Build an Apache Kafka® Connector
How to Build an Apache Kafka® Connectorconfluent
 
Streaming Design Patterns Using Alpakka Kafka Connector (Sean Glover, Lightbe...
Streaming Design Patterns Using Alpakka Kafka Connector (Sean Glover, Lightbe...Streaming Design Patterns Using Alpakka Kafka Connector (Sean Glover, Lightbe...
Streaming Design Patterns Using Alpakka Kafka Connector (Sean Glover, Lightbe...confluent
 
Developing Real-Time Data Pipelines with Apache Kafka
Developing Real-Time Data Pipelines with Apache KafkaDeveloping Real-Time Data Pipelines with Apache Kafka
Developing Real-Time Data Pipelines with Apache KafkaJoe Stein
 
Deploying Kafka Streams Applications with Docker and Kubernetes
Deploying Kafka Streams Applications with Docker and KubernetesDeploying Kafka Streams Applications with Docker and Kubernetes
Deploying Kafka Streams Applications with Docker and Kubernetesconfluent
 
Developing Realtime Data Pipelines With Apache Kafka
Developing Realtime Data Pipelines With Apache KafkaDeveloping Realtime Data Pipelines With Apache Kafka
Developing Realtime Data Pipelines With Apache KafkaJoe Stein
 
Stream analysis with kafka native way and considerations about monitoring as ...
Stream analysis with kafka native way and considerations about monitoring as ...Stream analysis with kafka native way and considerations about monitoring as ...
Stream analysis with kafka native way and considerations about monitoring as ...Andrew Yongjoon Kong
 

Ähnlich wie Testing Kafka components with Kafka for JUnit (20)

Exactly-once Stream Processing with Kafka Streams
Exactly-once Stream Processing with Kafka StreamsExactly-once Stream Processing with Kafka Streams
Exactly-once Stream Processing with Kafka Streams
 
Kafka Summit SF 2017 - Exactly-once Stream Processing with Kafka Streams
Kafka Summit SF 2017 - Exactly-once Stream Processing with Kafka StreamsKafka Summit SF 2017 - Exactly-once Stream Processing with Kafka Streams
Kafka Summit SF 2017 - Exactly-once Stream Processing with Kafka Streams
 
Maf3 - Part 1
Maf3 - Part 1Maf3 - Part 1
Maf3 - Part 1
 
Spark Streaming Info
Spark Streaming InfoSpark Streaming Info
Spark Streaming Info
 
Exactly-once Data Processing with Kafka Streams - July 27, 2017
Exactly-once Data Processing with Kafka Streams - July 27, 2017Exactly-once Data Processing with Kafka Streams - July 27, 2017
Exactly-once Data Processing with Kafka Streams - July 27, 2017
 
KAFKA Quickstart
KAFKA QuickstartKAFKA Quickstart
KAFKA Quickstart
 
How Scala promotes TDD
How Scala promotes TDDHow Scala promotes TDD
How Scala promotes TDD
 
Stream Processing made simple with Kafka
Stream Processing made simple with KafkaStream Processing made simple with Kafka
Stream Processing made simple with Kafka
 
Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...
Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...
Developing a custom Kafka connector? Make it shine! | Igor Buzatović, Porsche...
 
Kubernetes fundamentals
Kubernetes fundamentalsKubernetes fundamentals
Kubernetes fundamentals
 
I can't believe it's not a queue: Kafka and Spring
I can't believe it's not a queue: Kafka and SpringI can't believe it's not a queue: Kafka and Spring
I can't believe it's not a queue: Kafka and Spring
 
Secure Kafka at scale in true multi-tenant environment ( Vishnu Balusu & Asho...
Secure Kafka at scale in true multi-tenant environment ( Vishnu Balusu & Asho...Secure Kafka at scale in true multi-tenant environment ( Vishnu Balusu & Asho...
Secure Kafka at scale in true multi-tenant environment ( Vishnu Balusu & Asho...
 
Declarative benchmarking of cassandra and it's data models
Declarative benchmarking of cassandra and it's data modelsDeclarative benchmarking of cassandra and it's data models
Declarative benchmarking of cassandra and it's data models
 
TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...
TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...
TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...
 
How to Build an Apache Kafka® Connector
How to Build an Apache Kafka® ConnectorHow to Build an Apache Kafka® Connector
How to Build an Apache Kafka® Connector
 
Streaming Design Patterns Using Alpakka Kafka Connector (Sean Glover, Lightbe...
Streaming Design Patterns Using Alpakka Kafka Connector (Sean Glover, Lightbe...Streaming Design Patterns Using Alpakka Kafka Connector (Sean Glover, Lightbe...
Streaming Design Patterns Using Alpakka Kafka Connector (Sean Glover, Lightbe...
 
Developing Real-Time Data Pipelines with Apache Kafka
Developing Real-Time Data Pipelines with Apache KafkaDeveloping Real-Time Data Pipelines with Apache Kafka
Developing Real-Time Data Pipelines with Apache Kafka
 
Deploying Kafka Streams Applications with Docker and Kubernetes
Deploying Kafka Streams Applications with Docker and KubernetesDeploying Kafka Streams Applications with Docker and Kubernetes
Deploying Kafka Streams Applications with Docker and Kubernetes
 
Developing Realtime Data Pipelines With Apache Kafka
Developing Realtime Data Pipelines With Apache KafkaDeveloping Realtime Data Pipelines With Apache Kafka
Developing Realtime Data Pipelines With Apache Kafka
 
Stream analysis with kafka native way and considerations about monitoring as ...
Stream analysis with kafka native way and considerations about monitoring as ...Stream analysis with kafka native way and considerations about monitoring as ...
Stream analysis with kafka native way and considerations about monitoring as ...
 

Kürzlich hochgeladen

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 

Kürzlich hochgeladen (20)

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 

Testing Kafka components with Kafka for JUnit

  • 1. Markus Günther Freelance Software Engineer / Architect mail@mguenther.net | mguenther.net | @markus_guenther Apache Kafka Testing Kafka-enabled software components
  • 2. 2 There are several approaches to testing Kafka-enabled components or services. Problem Solution ▪ Spring Kafka provides an embeddable cluster ▪ Lacks the possiblity to work with external clusters ▪ Leads to boilerplate code in your test ▪ There are (costly) testing tools that are able to inject records into topics ▪ Lacks the possibility to work with embedded clusters ▪ Suitable for system testing, not integration testing ▪ Testing Kafka-based components or services is not trivial ▪ Need to have a working cluster ▪ Must be able to instrument the cluster ▪ Mocking is not an option for integration or system tests
  • 3. 3 Kafka for JUnit is suitable for integration testing as well as system testing. Solution ▪ Kafka for JUnit ▪ Works with embedded Kafka clusters – suitable for integration testing ▪ Works with external Kafka clusters – suitable for system testing ▪ Features a concise and readable API ▪ Features fault injection to trigger error handling ▪ Integrates well with Spring Kafka
  • 4. 4 Kafka for JUnit allows you to write integration tests that work against an embedded Kafka cluster. Integration Test JUNIT JUPITER Consumer / Producer KAFKA-BASED COMPONENT my.test.topic EMBEDDED APACHE KAFKA CLUSTER VERTICALS instruments provisions interacts with
  • 5. 6 Kafka for JUnit allows you to write system tests that work against an external Kafka cluster. VERTICALS Event Producer SERVICE A Event Consumer SERVICE B topic.for.events APACHE KAFKA CLUSTER System Test JUNIT JUPITER trigger use case observes topic for expected records publishes events consumes events
  • 6. 7 Kafka for JUnit provides abstractions for interacting with a Kafka cluster through EmbeddedKafkaCluster and ExternalKafkaCluster. my.test.topic APACHE KAFKA CLUSTER RecordProducer EmbeddedKafkaCluster RecordConsumer TopicManager FaultInjection my.test.topic APACHE KAFKA CLUSTER RecordProducer ExternalKafkaCluster RecordConsumer TopicManager
  • 7. 8 A RecordProducer provides the means to send key-value pairs or non-keyed values to a Kafka topic. public interface RecordProducer { <V> List<RecordMetadata> send(SendValues<V> sendRequest) throws ...; <V> List<RecordMetadata> send(SendValuesTransactional<V> sendRequest) throws ...; <K,V> List<RecordMetadata> send(SendKeyValues<K,V> sendRequest) throws ...; <K,V> List<RecordMetadata> send(SendKeyValuesTransactional<K,V> sendRequest) ...; /* overloaded methods that accept builder instances * for the resp. type have been omitted for brevity */ } Kafka for JUnit provides builders for these requests! Interface definition of RecordProducer
  • 8. 9 Publishing data to a Kafka topic is as simple as contributing a one-liner in the default case. kafka.send(SendValues.to(“my.test.topic“, “a“, “b“, “c“)); Sending non-keyed values using defaults kafka.send(SendValuesTransactional.inTransaction( “my.test.topic“, Arrays.asList(“a“, “b“, “c“))); kafka.send(SendValues.to(“my.test.topic“, “a“, “b“, “c“)) .with(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, “true“) .with(ProducerConfig.MAX_IN_FLIGHT_REQUEST_PER_CONNECTION, “1“)); Sending non-keyed values using overrides Sending non-keyed values transactionally
  • 9. 1 A RecordConsumer provides the means to read data from a topic or observe a topic until some criteria is met or a timeout elapses. public interface RecordConsumer { <V> List<V> readValues(ReadKeyValues<String,V> readRequest) throws ...; <K,V> List<KeyValue<K,V>> read(ReadKeyValues<K,V> readRequest) throws ...; <V> List<V> observeValues(ObserveKeyValues<String,V> observeRequest) throws ...; <K,V> List<KeyValue<K,V>> observe(ObserveKeyValues<K,V> observeRequest) throws ...; /* overloaded methods that accept builder instances * for the resp. type have been omitted for brevity */ } Kafka for JUnit provides builders for these requests! Interface definition of RecordConsumer
  • 10. 1 Consuming records is just as easy as producing them. val values = kafka.readValues(ReadKeyValues.from(“my.test.topic“)); Consuming only values using defaults List<KeyValue<String, Long>> records = kafka.read(ReadKeyValues .from(“my.test.topic“, Long.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ...)); val records = kafka.read(ReadKeyValues.from(“my.test.topic“)); Consuming key-value pairs using defaults Consuming key-value pairs using overrides
  • 11. 1 Observations can be used to let a test fail unless given criteria are met. kafka.observeValues(ObserveKeyValues.on(“my.test.topic“, 3)); Observing a topic until n values have been consumed val keyFilter = Integer.parseInt(k) % 2 == 0; kafka.observe(ObserveKeyValues.on(“my.test.topic“, 3, Integer.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ...) .filterOnKeys(keyFilter)); List<KeyValue<String,String>> observedRecords = kafka .observe(ObserveKeyValues.on(“my.test.topic“, 3)); Observing a topic until n records have been consumed Using filters when consuming or observing a topic
  • 12. 1 A TopicManager provides the means to manage Kafka topics. public interface TopicManager { void createTopic(TopicConfig config); void deleteTopic(String topic); boolean exists(String topic); Map<Integer, LeaderAndIsr> fetchLeaderAndIsr(String topic); Properties fetchTopicConfig(String topic); /* overloaded methods that accept builder instances for the resp. type have been omitted for brevity */ } Kafka for JUnit provides builders for these requests! Interface definition of TopicManager
  • 13. 1 The default TopicManager implementation leverages the AdminClient implementation of the Kafka Client library. kafka.createTopic(TopicConfig.withName(“my.test.topic“)); Creating a topic using defaults kafka.deleteTopic(“my.test.topic“); Deleting a topic kafka.createTopic(TopicConfig.withName(“my.test.topic“) .withNumberOfPartitions(5) .withNumberOfReplicas(1)); Creating a topic with specific properties
  • 14. 1 Writing integration tests with Kafka for JUnit
  • 15. 1 Let’s write a test that exercises the write-path of Kafka-based component. TurbineEventPublisherTest JUNIT JUPITER TurbineEventPublisher TURBINE REGISTRY turbine.lifecycle.events EMBEDDED APACHE KAFKA CLUSTER instruments provisions interacts with
  • 16. 1
  • 17. 1 Let’s write a simple test that verifies that TurbineEventPublisher is able to write events to the designated topic. public class TurbineEventPublisherTest { private EmbeddedKafkaCluster kafka; @BeforeEach void setupKafka() { kafka = provisionWith(defaultClusterConfig()); kafka.start(); } @AfterEach void tearDownKafka() { kafka.stop(); } } Provide the skeleton for the component test incl. a workable Kafka cluster. static import from ExternalKafkaCluster static import from ExternalKafkaClusterConfig
  • 18. 1 The observe method throws an AssertionError once a certain configurable amount of time has elapsed. var config = Map.<String, Object>of( ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBrokerList()); var publisher = new TurbineEventPublisher(“turbine.lifecycle.events“, config); var event = new TurbineRegisteredEvent(“1a5c6012“, 49.875114, 8.978702); publisher.log(event); Create an instance of the subject-under-test and publish test data
  • 19. 2 The observe method throws an AssertionError once a certain configurable amount of time has elapsed. (cont.) kafka.observe(ObserveKeyValues .on(“turbine.lifecycle.events“, 1, TurbineEvent.class) .observeFor(15, TimeUnit.SECONDS) .filterOnKeys(key -> key.equals(“1a5c6012“)) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, TurbineEventDeserializer.class)); Observe the designated topic for new data override arbitrary consumer properties the topic we want to observe the number of records we expect the value type of the expected records use filters to add observation criterias
  • 20. 2 The observe method returns all records that it obtained from watching the topic. var record = kafka.observe( on(“turbine.lifecycle.events“, 1, TurbineEvent.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, TurbineEventDeserializer.class)) .stream() .findFirst() .orElseThrow(AssertionError::new); assertThat(record.getKey()).isEqualTo(“1a5c6012“); assertThat(record.getValue()).isInstanceOf(TurbineRegisteredEvent.class); Fetch observed records and assert that their data is what you expect it to be
  • 21. 2 Writing systems tests with Kafka for JUnit
  • 22. 2
  • 23. 2 We’ll use a simple client interface to provide the means to exert an external stimulus on the system. (cont.) Listing 1: Example for Feign-based HTTP client that interacts with the system public interface GettingThingsDone { @RequestLine(“POST /items“) @Headers(“Content-Type: application/json“) Response createItem(CreateItem payload); @RequestLine(“GET /items/{itemId}“) @Headers(“Accept: application/json“) Item getItem(@Param(“itemId“) String itemId); /* additional methods omitted for brevity */ } Example for Feign-based HTTP client that interacts with the system
  • 24. 2 We’ll use a simple client interface to provide the means to exert an external stimulus on the system. (cont.) Listing 1: Example for Feign-based HTTP client that interacts with the system val kafka = ExternalKafkaCluster.at(“http://localhost:9092“); Gain programmatic access to the cluster val itemId = extractItemId(response); Extract the ID of the newly created item from the response val gtd = createGettingThingsDoneClient(); val payload = new CreateItem(“Buy groceries!“); val response = gtd.createItem(payload) Trigger a use case using the client interface
  • 25. 2 Leverage Kafka for JUnit to observe the designated topic and apply assertions on the returned records. Listing 1: Example for Feign-based HTTP client that interacts with the system List<AvroItemEvent> publishedEvents = kafka .observeValues(on(“item.events“, 1, AvroItemEvent.class) .observeFor(10, TimeUnit.SECONDS) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ItemEventDeserializer.class) .filterOnKeys(aggregateId -> aggregateId.equals(itemId))); Observe the designated topic for the throws an AssertionError if the timeout elapses
  • 26. 2 Want to know more? GitHub Blog ▪ Günther, M., Writing component tests for Kafka producers, https://bit.ly/39NpoCU ▪ Günther, M., Writing component tests for Kafka consumers, https://bit.ly/36KrXoV ▪ Günther, M., Writing system tests for a Kafka-enabled microservice, https://bit.ly/2OUeEMs ▪ Günther, M., Using Kafka for JUnit with Spring Kafka, https://bit.ly/3c61WSx ▪ Kafka for JUnit on GitHub, https://mguenther.github.io/kafka-junit/ ▪ User Guide to Kafka for JUnit, https://mguenther.github.io/kafka-junit/