Java / Maven

Testing Kafka Listener using Testcontainers with the Micronaut Framework

This guide shows how to test a Kafka Listener using Testcontainers in a Micronaut Framework application.

Sergio del Amo
On this guide
In this section

In this guide you will learn how to

What you will need

To complete this guide, you will need the following:

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

What we are going to achieve in this guide

We are going to create a Micronaut project with Kafka, Micronaut Data JPA and MySQL, where we implement a Kafka Listener which receives an event payload and persists the event data in the database. Then we will test this Kafka Listener using the Testcontainers Kafka and MySQL modules in conjunction with Awaitility.

The generated application has Awaitility library as test dependency which we can use for asserting the expectations of an asynchronous process flow.

Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide \
    --features=assertj,data-jpa,kafka,testcontainers,mysql,awaitility \
    --build=maven \
    --lang=java
Note
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

If you use Micronaut Launch, select Micronaut Application as application type and add assertj, data-jpa, kafka, testcontainers, mysql, and awaitility features.

Note
If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application.

Testcontainers Dependencies

The generated application contains the following Testcontainers dependencies:

pom.xml
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>testcontainers-kafka</artifactId>
    <scope>test</scope>
</dependency>
pom.xml
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>testcontainers-mysql</artifactId>
    <scope>test</scope>
</dependency>

Datasource Configuration

The generated application contains the following configuration:

testcontainers/java/src/main/resources/application.properties
datasources.default.db-type=mysql
datasources.default.dialect=MYSQL
jpa.default.properties.hibernate.hbm2ddl.auto=update
jpa.default.entity-scan.packages=example.micronaut
datasources.default.driver-class-name=com.mysql.cj.jdbc.Driver
Note
Note the configuration does not contain any database URL, username or password. It does not contain the Kafka bootstrap servers' location either. We will configure them in the test or via Micronaut Test Resources.

Getting Started

We are going to implement a Kafka Listener listening to a topic named product-price-changes and upon receiving a message we are going to extract product code and price from the event payload and update the price of that product in the MySQL database.

Create JPA entity

First let us start with creating a JPA entity Product.java.

testcontainers/java/src/main/java/example/micronaut/Product.java
package example.micronaut;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

import java.math.BigDecimal;

@Entity
@Table(name = "products")
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String code;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private BigDecimal price;

    public Product() {}

    public Product(Long id, String code, String name, BigDecimal price) {
        this.id = id;
        this.code = code;
        this.name = name;
        this.price = price;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }
}

Create Micronaut Data JPA repository

Let us create a Micronaut Data JPA repository interface for the Product entity and add methods to find a product for a given code and update the price for the given product code as follows:

testcontainers/java/src/main/java/example/micronaut/ProductRepository.java

Create the event payload java bean

Let us create a domain object named ProductPriceChangedEvent as a record representing the structure of the event payload that we are going to receive from the Kafka topic.

testcontainers/java/src/main/java/example/micronaut/ProductPriceChangedEvent.java

Implement Kafka Listener

Finally, let us implement the Kafka listener which handles the messages received from the product-price-changes topic and updates the product price in the database.

To listen to Kafka messages you can use the @KafkaListener annotation to define a message listener.

testcontainers/java/src/main/java/example/micronaut/ProductPriceChangedEventHandler.java

Let us assume that there is an agreement between the sender and receiver that the payload will be sent in the following JSON format:

{
    "productCode": "P100",
    "price": 25.00
}

Testing

Write Test for Kafka Listener

We are going to write a test for the Kafka event listener ProductPriceChangedEventHandler by sending a message to the product-price-changes topic and verify the updated product price in the database.

But in order to successfully start our Micronaut context we need Kafka and the MySQL database up and running and configure the Micronaut context to talk to them.

Create a @KafkaClient to simplify publishing events in the test.

testcontainers/java/src/test/java/example/micronaut/ProductPriceChangesClient.java

We will use the Testcontainers library to spin up a Kafka and the MySQL database instances as Docker containers and configure the application to talk to them as follows:

testcontainers/java/src/test/java/example/micronaut/ProductPriceChangedEventHandlerTest.java

Testing the Application

To run the tests:

./mvnw test

You should see the Kafka and MySQL Docker containers are started and all tests should PASS.

You can also notice that after the tests are executed the containers are stopped and removed automatically.

Testing Kafka integration with Test Resources

We are going to simplify testing with Micronaut Test Resources:

Micronaut Test Resources adds support for managing external resources which are required during development or testing.

Removing Testcontainers Dependencies

Remove the Testcontainers dependencies from your build files.

Configure Test Resources

You can enable test resources support simply by setting the property micronaut.test.resources.enabled (either in your POM or via the command-line).

Test Resources Kafka

When the application is started locally, either under test or while running locally, resolution of the property kafka.bootstrap.servers is detected and the Test Resources service will start a local Kafka docker container, and inject the properties required to use this as the broker.

Simpler Test with Test Resources

Thanks to Test Resources, we can simplify the test as follows:

testresources/java/src/test/java/example/micronaut/ProductPriceChangedEventHandlerTest.java

If you run the test, you will see a MySQL container and Kafka container being started by Test Resources through integration with Testcontainers to provide throwaway containers for testing.

Micronaut Test Resources Goals

  • zero-configuration: without adding any configuration, test resources should be spawned and the application configured to use them. Configuration is only required for advanced use cases.

  • classpath isolation: use of test resources shouldn’t leak into your application classpath, nor your test classpath

  • compatible with GraalVM native: if you build a native binary, or run tests in native mode, test resources should be available

  • easy to use: the Micronaut build plugins for Gradle and Maven should handle the complexity of figuring out the dependencies for you

  • extensible: you can implement your own test resources, in case the built-in ones do not cover your use case

  • technology agnostic: while lots of test resources use Testcontainers under the hood, you can use any other technology to create resources

Summary

We have learned how to test Kafka message listeners using a real Kafka instance with Testcontainers and verified the expected result using Awaitility. If we are using Kafka and MySQL in production, it is often the best approach to test with real Kafka and MySQL instances in order to allow our test suite to provide us with more confidence about the correctness of our code.

Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

License

Note
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images).