|
| 1 | +:toc: preamble |
| 2 | + |
| 3 | +# Spring Test Kafka |
| 4 | + |
| 5 | +image:https://travis-ci.com/jupiter-tools/spring-test-kafka.svg?branch=master["Build Status", link="https://travis-ci.com/jupiter-tools/spring-test-kafka"] |
| 6 | +image:https://codecov.io/gh/jupiter-tools/spring-test-kafka/branch/master/graph/badge.svg["", link="https://codecov.io/gh/jupiter-tools/spring-test-kafka"] |
| 7 | + |
| 8 | +Tools to write integration tests of Spring Framework with Redis. |
| 9 | + |
| 10 | +## Overview |
| 11 | + |
| 12 | +image:./images/spring-test-kafka-containers.png[redis container scheme] |
| 13 | + |
| 14 | +## How to write integration tests on Spring Boot with Apache Kafka |
| 15 | + |
| 16 | +Add this library in dependencies: |
| 17 | + |
| 18 | +[source,xml] |
| 19 | +---- |
| 20 | +<dependency> |
| 21 | + <groupId>com.jupiter-tools</groupId> |
| 22 | + <artifactId>spring-test-kafka</artifactId> |
| 23 | + <version>0.1</version> |
| 24 | +</dependency> |
| 25 | +---- |
| 26 | + |
| 27 | +Now, you can start Kafka in docker (TestContainers) by the using of `@KafkaTestContainer` annotation in tests: |
| 28 | + |
| 29 | +[source, java] |
| 30 | +---- |
| 31 | +@SpringBootTest |
| 32 | +@KafkaTestContainer |
| 33 | +class RedisTestContainerTest { |
| 34 | +
|
| 35 | + @Autowired |
| 36 | + private KafkaTemplate<String, String> kafkaTemplate; |
| 37 | +
|
| 38 | + @Test |
| 39 | + void sendAndReceiveTest() throws InterruptedException { |
| 40 | + assertThat(kafkaTemplate).isNotNull(); |
| 41 | + kafkaTemplate.send("test-topic", "flight of a dragon"); |
| 42 | + ... |
| 43 | + } |
| 44 | +} |
| 45 | +---- |
| 46 | + |
| 47 | +You can use this annotation to start Kafka container in tests both with JUnit5 and JUnit4. |
| 48 | +The implementation doesn't depend on some test framework, just on the Spring Framework. |
| 49 | + |
| 50 | +## How to use multiple Kafka containers in the one test case: |
| 51 | + |
| 52 | +[source, java] |
| 53 | +---- |
| 54 | +@SpringBootTest |
| 55 | +@KafkaTestContainer <1> |
| 56 | +@KafkaTestContainer(bootstrapServersPropertyName = "second.kafka.server") <2> |
| 57 | +class MultipleContainerInOneTest { |
| 58 | +
|
| 59 | + ... |
| 60 | +
|
| 61 | +} |
| 62 | +---- |
| 63 | +<1> start a first Kafka test container and set a bootstrap servers of started container to default Spring Boot properties (`spring.kafka.bootstrap-servers`) |
| 64 | +<2> start one more Kafka container and set a bootstrap servers to specified property, exactly in this property you can read an actual value of bootstrap servers after run the application context. |
0 commit comments