1
0
Files
spring-messaging-demo/kafka-basics/src/test/java/com/ankurm/kafkabasics/TestcontainersConfiguration.java

46 lines
2.1 KiB
Java

package com.ankurm.kafkabasics;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;
import org.testcontainers.kafka.KafkaContainer;
import org.testcontainers.utility.DockerImageName;
/**
* The Testcontainers route. Import this instead of {@code @EmbeddedKafka} when you want the same
* broker image your production cluster runs, or when you are testing something the in-process
* broker does not model (real network partitions, TLS, SASL, quotas).
*
* <p>{@code @ServiceConnection} is what makes this ergonomic: it registers the container's
* bootstrap servers as the application's, so there is no
* {@code @DynamicPropertySource} block and no {@code spring.kafka.bootstrap-servers} to keep in
* sync. It replaced that boilerplate in Boot 3.1 and is the only shape worth writing now.
*
* <p>Two coordinates matter and both changed recently:
* <ul>
* <li>the Maven artifact is <b>{@code org.testcontainers:testcontainers-kafka}</b>, not
* {@code org.testcontainers:kafka}, which stopped at 1.21.4</li>
* <li>the class is <b>{@code org.testcontainers.kafka.KafkaContainer}</b> (Apache Kafka,
* KRaft, no ZooKeeper), not {@code org.testcontainers.containers.KafkaContainer}</li>
* </ul>
*
* <p>The transcripts under {@code docs/output/} were NOT produced by this class &mdash; they came
* from the in-process KRaft broker, because the machine that regenerates them has no Docker
* daemon. Both paths run the same tests.
*
* @see <a href="../../../../../docs/07-testing.md">docs/07-testing.md</a>
*/
@TestConfiguration(proxyBeanMethods = false)
public class TestcontainersConfiguration {
// @RestartScope from spring-boot-devtools is worth adding here if you use `bootTestRun`:
// it keeps the container alive across devtools restarts. It needs the devtools dependency,
// which this module deliberately does not have.
@Bean
@ServiceConnection
KafkaContainer kafkaContainer() {
return new KafkaContainer(DockerImageName.parse("apache/kafka:4.1.0"));
}
}