此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring for Apache Kafka 3.3.9! |
测试应用程序
这spring-kafka-test
jar 包含一些有用的实用程序来帮助测试您的应用程序。
嵌入式 Kafka 代理
由于 Kafka 4.0 已完全过渡到 KRaft 模式,因此只有EmbeddedKafkaKraftBroker
现已推出实施:
-
EmbeddedKafkaKraftBroker
-使用Kraft
在控制器和代理组合模式下。
有几种技术可以配置代理,如以下部分所述。
KafkaTestUtils
org.springframework.kafka.test.utils.KafkaTestUtils
提供了许多静态帮助程序方法来使用记录、检索各种记录偏移量等。
有关完整详细信息,请参阅其 Javadocs。
JUnit
org.springframework.kafka.test.utils.KafkaTestUtils
提供了一些静态方法来设置生产者和消费者属性。
以下列表显示了这些方法签名:
/**
* Set up test properties for an {@code <Integer, String>} consumer.
* @param group the group id.
* @param autoCommit the auto commit.
* @param embeddedKafka a {@link EmbeddedKafkaBroker} instance.
* @return the properties.
*/
public static Map<String, Object> consumerProps(String group, String autoCommit,
EmbeddedKafkaBroker embeddedKafka) { ... }
/**
* Set up test properties for an {@code <Integer, String>} producer.
* @param embeddedKafka a {@link EmbeddedKafkaBroker} instance.
* @return the properties.
*/
public static Map<String, Object> producerProps(EmbeddedKafkaBroker embeddedKafka) { ... }
从 2.5 版开始, 使用嵌入式代理时,通常最佳做法是为每个测试使用不同的主题,以防止串扰。
如果由于某种原因无法做到这一点,请注意 |
Spring for Apache Kafka 不再支持 JUnit 4。 建议迁移到 JUnit Jupiter。 |
这EmbeddedKafkaBroker
class 有一个实用方法,可让您使用它创建的所有主题。
以下示例演示如何使用它:
Map<String, Object> consumerProps = KafkaTestUtils.consumerProps("testT", "false", embeddedKafka);
DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(consumerProps);
Consumer<Integer, String> consumer = cf.createConsumer();
embeddedKafka.consumeFromAllEmbeddedTopics(consumer);
这KafkaTestUtils
有一些实用方法可以从消费者那里获取结果。
以下列表显示了这些方法签名:
/**
* Poll the consumer, expecting a single record for the specified topic.
* @param consumer the consumer.
* @param topic the topic.
* @return the record.
* @throws org.junit.ComparisonFailure if exactly one record is not received.
*/
public static <K, V> ConsumerRecord<K, V> getSingleRecord(Consumer<K, V> consumer, String topic) { ... }
/**
* Poll the consumer for records.
* @param consumer the consumer.
* @return the records.
*/
public static <K, V> ConsumerRecords<K, V> getRecords(Consumer<K, V> consumer) { ... }
以下示例演示如何使用KafkaTestUtils
:
...
template.sendDefault(0, 2, "bar");
ConsumerRecord<Integer, String> received = KafkaTestUtils.getSingleRecord(consumer, "topic");
...
当嵌入式 Kafka 代理由EmbeddedKafkaBroker
,一个名为spring.embedded.kafka.brokers
设置为 Kafka 代理的地址。
方便的常量 (EmbeddedKafkaBroker.SPRING_EMBEDDED_KAFKA_BROKERS
) 为该物业提供。
而不是默认spring.embedded.kafka.brokers
系统属性,Kafka 代理的地址可以暴露给任何任意且方便的属性。
为此,一个spring.embedded.kafka.brokers.property
(EmbeddedKafkaBroker.BROKER_LIST_PROPERTY
) 系统属性可以在启动嵌入式 Kafka 之前设置。
例如,使用 Spring Bootspring.kafka.bootstrap-servers
配置属性应分别为自动配置 Kafka 客户端设置。
因此,在随机端口上使用嵌入式 Kafka 运行测试之前,我们可以将spring.embedded.kafka.brokers.property=spring.kafka.bootstrap-servers
作为系统属性 - 和EmbeddedKafkaBroker
将使用它来公开其代理地址。
这现在是此属性的默认值(从版本 3.0.10 开始)。
使用EmbeddedKafkaBroker.brokerProperties(Map<String, String>)
,您可以为 Kafka 服务器提供其他属性。
有关可能的代理属性的更多信息,请参阅 Kafka Config。
配置主题
以下示例配置创建名为cat
和hat
有五个分区,一个名为thing1
有 10 个分区,以及一个名为thing2
有 15 个分区:
@SpringJUnitConfig
@EmbeddedKafka(
partitions = 5,
topics = {"cat", "hat"}
)
public class MyTests {
@Autowired
private EmbeddedKafkaBroker broker;
@Test
public void test() {
broker.addTopics(new NewTopic("thing1", 10, (short) 1), new NewTopic("thing2", 15, (short) 1));
...
}
}
默认情况下,addTopics
当出现问题时(例如添加已经存在的主题)将抛出异常。
版本 2.6 添加了该方法的新版本,该方法返回Map<String, Exception>
;键是主题名称,值是null
成功,或Exception
失败。
对多个测试类使用相同的代理
您可以对多个测试类使用相同的代理,类似于以下内容:
public final class EmbeddedKafkaHolder {
private static EmbeddedKafkaBroker embeddedKafka = new EmbeddedKafkaZKBroker(1, false)
.brokerListProperty("spring.kafka.bootstrap-servers");
private static boolean started;
public static EmbeddedKafkaBroker getEmbeddedKafka() {
if (!started) {
synchronized (this) {
if (!started) {
try {
embeddedKafka.afterPropertiesSet();
}
catch (Exception e) {
throw new KafkaException("Embedded broker failed to start", e);
}
started = true;
}
}
}
return embeddedKafka;
}
}
这假设有一个 Spring Boot 环境,嵌入式代理替换了引导服务器属性。
然后,在每个测试类中,您可以使用类似于以下内容的内容:
static {
EmbeddedKafkaHolder.getEmbeddedKafka().addTopics("topic1", "topic2");
}
private static final EmbeddedKafkaBroker broker = EmbeddedKafkaHolder.getEmbeddedKafka();
如果您不使用 Spring Boot,您可以使用以下命令获取引导服务器broker.getBrokersAsString()
.
前面的示例没有提供在所有测试完成后关闭代理的机制。
例如,如果您在 Gradle 守护进程中运行测试,这可能会成为问题。
在这种情况下,您不应该使用此技术,或者您应该使用一些东西来调用destroy() 在EmbeddedKafkaBroker 当您的测试完成时。 |
从 3.0 版开始,该框架公开了GlobalEmbeddedKafkaTestExecutionListener
用于 JUnit 平台;默认情况下,它是禁用的。
这需要 JUnit Platform 1.8 或更高版本。
此侦听器的目的是启动一个全局EmbeddedKafkaBroker
在整个测试计划结束时停止它。
要启用此侦听器,从而为项目中的所有测试提供一个全局嵌入式 Kafka 集群,请spring.kafka.global.embedded.enabled
属性必须设置为true
通过系统属性或 JUnit 平台配置。
此外,还可以提供以下属性:
-
spring.kafka.embedded.count
- 要管理的 Kafka 代理数量; -
spring.kafka.embedded.ports
- 每个 Kafka 代理启动的端口(逗号分隔值),0
如果首选随机端口;值的数量必须等于count
上述; -
spring.kafka.embedded.topics
- 在启动的 Kafka 集群中创建的主题(逗号分隔值); -
spring.kafka.embedded.partitions
- 要为创建的主题配置的分区数; -
spring.kafka.embedded.broker.properties.location
- 其他 Kafka 代理配置属性的文件位置;此属性的值必须遵循 Spring 资源抽象模式。
从本质上讲,这些属性模仿了@EmbeddedKafka
属性。
有关配置属性以及如何提供它们的更多信息,请参阅 JUnit Jupiter 用户指南。
例如,一个spring.embedded.kafka.brokers.property=my.bootstrap-servers
条目可以添加到junit-platform.properties
测试类路径中的文件。
从 3.0.10 版开始,代理会自动将其设置为spring.kafka.bootstrap-servers
,默认情况下,用于使用 Spring Boot 应用程序进行测试。
建议不要将全局嵌入式 Kafka 和每个测试类组合在单个测试套件中。 它们都具有相同的系统属性,因此很可能会导致意外行为。 |
spring-kafka-test 对junit-jupiter-api 和junit-platform-launcher (后者支持全局嵌入式代理)。
如果您希望使用嵌入式代理并且不使用 JUnit,您可能希望排除这些依赖项。 |
@EmbeddedKafka
注解
我们通常建议您使用单个代理实例,以避免在测试之间启动和停止代理(并为每个测试使用不同的主题)。
从 2.0 版本开始,如果您使用 Spring 的测试应用程序上下文缓存,您还可以声明一个EmbeddedKafkaBroker
bean,因此单个代理可以跨多个测试类使用。
为方便起见,我们提供了一个名为@EmbeddedKafka
以注册EmbeddedKafkaBroker
豆。
以下示例演示如何使用它:
@SpringJUnitConfig
@DirtiesContext
@EmbeddedKafka(partitions = 1,
topics = {
KafkaStreamsTests.STREAMING_TOPIC1,
KafkaStreamsTests.STREAMING_TOPIC2 })
public class KafkaStreamsTests {
@Autowired
private EmbeddedKafkaBroker embeddedKafka;
@Test
void someTest() {
Map<String, Object> consumerProps = KafkaTestUtils.consumerProps("testGroup", "true", this.embeddedKafka);
consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
ConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(consumerProps);
Consumer<Integer, String> consumer = cf.createConsumer();
this.embeddedKafka.consumeFromAnEmbeddedTopic(consumer, KafkaStreamsTests.STREAMING_TOPIC2);
ConsumerRecords<Integer, String> replies = KafkaTestUtils.getRecords(consumer);
assertThat(replies.count()).isGreaterThanOrEqualTo(1);
}
@Configuration
@EnableKafkaStreams
public static class TestKafkaStreamsConfiguration {
@Value("${" + EmbeddedKafkaBroker.SPRING_EMBEDDED_KAFKA_BROKERS + "}")
private String brokerAddresses;
@Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
public KafkaStreamsConfiguration kStreamsConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "testStreams");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, this.brokerAddresses);
return new KafkaStreamsConfiguration(props);
}
}
}
从 2.2.4 版开始,您还可以使用@EmbeddedKafka
注释来指定 Kafka 端口属性。
从 4.0 版本开始,所有与 ZooKeeper 相关的属性都已从@EmbeddedKafka 注释,因为 Kafka 4.0 专门使用 KRaft。 |
以下示例将topics
,brokerProperties
和brokerPropertiesLocation
属性@EmbeddedKafka
支持属性占位符解析:
@TestPropertySource(locations = "classpath:/test.properties")
@EmbeddedKafka(topics = { "any-topic", "${kafka.topics.another-topic}" },
brokerProperties = { "log.dir=${kafka.broker.logs-dir}",
"listeners=PLAINTEXT://localhost:${kafka.broker.port}",
"auto.create.topics.enable=${kafka.broker.topics-enable:true}" },
brokerPropertiesLocation = "classpath:/broker.properties")
在前面的示例中,属性占位符${kafka.topics.another-topic}
,${kafka.broker.logs-dir}
和${kafka.broker.port}
从 Spring 解析Environment
.
此外,代理属性是从broker.properties
classpath 资源由brokerPropertiesLocation
.
属性占位符已解析为brokerPropertiesLocation
URL 和资源中找到的任何属性占位符。
属性定义brokerProperties
覆盖在brokerPropertiesLocation
.
您可以使用@EmbeddedKafka
使用 JUnit Jupiter 进行注释。
@EmbeddedKafka
使用 JUnit Jupiter 进行注释
从 2.3 版开始,有两种方法可以使用@EmbeddedKafka
使用 JUnit Jupiter 进行注释。
当与@SpringJunitConfig
注释,则将嵌入式代理添加到测试应用程序上下文中。
您可以在类或方法级别自动将代理连接到测试中,以获取代理地址列表。
当不使用 spring test 上下文时,EmbdeddedKafkaCondition
创建经纪人;该条件包括一个参数解析器,以便您可以在测试方法中访问代理。
@EmbeddedKafka
public class EmbeddedKafkaConditionTests {
@Test
public void test(EmbeddedKafkaBroker broker) {
String brokerList = broker.getBrokersAsString();
...
}
}
将创建一个独立代理(在 Spring 的 TestContext 之外),除非类被注释@EmbeddedKafka
也用ExtendWith(SpringExtension.class)
.@SpringJunitConfig
和@SpringBootTest
是如此元注释,并且当这些注释中的任何一个也存在时,将使用基于上下文的代理。
当有可用的 Spring 测试应用程序上下文时,主题和代理属性可以包含属性占位符,只要在某处定义了属性,这些占位符就会被解析。 如果没有可用的 Spring 上下文,则不会解析这些占位符。 |
嵌入式代理@SpringBootTest
附注
Spring Initializr 现在会自动添加spring-kafka-test
测试范围内对项目配置的依赖关系。
如果您的应用程序在
|
有几种方法可以在 Spring Boot 应用程序测试中使用嵌入式代理。
他们包括:
@EmbeddedKafka
跟@SpringJunitConfig
使用时@EmbeddedKafka
跟@SpringJUnitConfig
,建议使用@DirtiesContext
在测试类上。这是为了防止在测试套件中运行多个测试后在 JVM 关闭期间发生潜在的竞争条件。例如,不使用@DirtiesContext
这EmbeddedKafkaBroker
可能会提前关闭,而应用程序上下文仍需要来自它的资源。由于每个EmbeddedKafka
test-runs 创建自己的临时目录,当发生此竞争条件时,它将生成错误日志消息,指示它尝试删除或清理的文件不再可用。 添加@DirtiesContext
将确保应用程序上下文在每次测试后被清理并且不缓存,从而使其不易受到此类潜在资源竞争条件的影响。
@EmbeddedKafka
注释或EmbeddedKafkaBroker
豆
以下示例演示如何使用@EmbeddedKafka
用于创建嵌入式代理的注释:
@SpringJUnitConfig
@EmbeddedKafka(topics = "someTopic",
bootstrapServersProperty = "spring.kafka.bootstrap-servers") // this is now the default
public class MyApplicationTests {
@Autowired
private KafkaTemplate<String, String> template;
@Test
void test() {
...
}
}
这bootstrapServersProperty 自动设置为spring.kafka.bootstrap-servers 默认情况下,从 3.0.10 版本开始。 |
Hamcrest 匹配器
这org.springframework.kafka.test.hamcrest.KafkaMatchers
提供以下匹配器:
/**
* @param key the key
* @param <K> the type.
* @return a Matcher that matches the key in a consumer record.
*/
public static <K> Matcher<ConsumerRecord<K, ?>> hasKey(K key) { ... }
/**
* @param value the value.
* @param <V> the type.
* @return a Matcher that matches the value in a consumer record.
*/
public static <V> Matcher<ConsumerRecord<?, V>> hasValue(V value) { ... }
/**
* @param partition the partition.
* @return a Matcher that matches the partition in a consumer record.
*/
public static Matcher<ConsumerRecord<?, ?>> hasPartition(int partition) { ... }
/**
* Matcher testing the timestamp of a {@link ConsumerRecord} assuming the topic has been set with
* {@link org.apache.kafka.common.record.TimestampType#CREATE_TIME CreateTime}.
*
* @param ts timestamp of the consumer record.
* @return a Matcher that matches the timestamp in a consumer record.
*/
public static Matcher<ConsumerRecord<?, ?>> hasTimestamp(long ts) {
return hasTimestamp(TimestampType.CREATE_TIME, ts);
}
/**
* Matcher testing the timestamp of a {@link ConsumerRecord}
* @param type timestamp type of the record
* @param ts timestamp of the consumer record.
* @return a Matcher that matches the timestamp in a consumer record.
*/
public static Matcher<ConsumerRecord<?, ?>> hasTimestamp(TimestampType type, long ts) {
return new ConsumerRecordTimestampMatcher(type, ts);
}
AssertJ 条件
您可以使用以下 AssertJ 条件:
/**
* @param key the key
* @param <K> the type.
* @return a Condition that matches the key in a consumer record.
*/
public static <K> Condition<ConsumerRecord<K, ?>> key(K key) { ... }
/**
* @param value the value.
* @param <V> the type.
* @return a Condition that matches the value in a consumer record.
*/
public static <V> Condition<ConsumerRecord<?, V>> value(V value) { ... }
/**
* @param key the key.
* @param value the value.
* @param <K> the key type.
* @param <V> the value type.
* @return a Condition that matches the key in a consumer record.
* @since 2.2.12
*/
public static <K, V> Condition<ConsumerRecord<K, V>> keyValue(K key, V value) { ... }
/**
* @param partition the partition.
* @return a Condition that matches the partition in a consumer record.
*/
public static Condition<ConsumerRecord<?, ?>> partition(int partition) { ... }
/**
* @param value the timestamp.
* @return a Condition that matches the timestamp value in a consumer record.
*/
public static Condition<ConsumerRecord<?, ?>> timestamp(long value) {
return new ConsumerRecordTimestampCondition(TimestampType.CREATE_TIME, value);
}
/**
* @param type the type of timestamp
* @param value the timestamp.
* @return a Condition that matches the timestamp value in a consumer record.
*/
public static Condition<ConsumerRecord<?, ?>> timestamp(TimestampType type, long value) {
return new ConsumerRecordTimestampCondition(type, value);
}
示例
以下示例汇集了本章中涵盖的大多数主题:
@EmbeddedKafka(topics = KafkaTemplateTests.TEMPLATE_TOPIC)
public class KafkaTemplateTests {
public static final String TEMPLATE_TOPIC = "templateTopic";
@BeforeAll
public static void setUp() {
embeddedKafka = EmbeddedKafkaCondition.getBroker();
}
@Test
public void testTemplate() throws Exception {
Map<String, Object> consumerProps = KafkaTestUtils.consumerProps("testT", "false",
embeddedKafka);
DefaultKafkaConsumerFactory<Integer, String> cf =
new DefaultKafkaConsumerFactory<>(consumerProps);
ContainerProperties containerProperties = new ContainerProperties(TEMPLATE_TOPIC);
KafkaMessageListenerContainer<Integer, String> container =
new KafkaMessageListenerContainer<>(cf, containerProperties);
final BlockingQueue<ConsumerRecord<Integer, String>> records = new LinkedBlockingQueue<>();
container.setupMessageListener(new MessageListener<Integer, String>() {
@Override
public void onMessage(ConsumerRecord<Integer, String> record) {
System.out.println(record);
records.add(record);
}
});
container.setBeanName("templateTests");
container.start();
ContainerTestUtils.waitForAssignment(container,
embeddedKafka.getPartitionsPerTopic());
Map<String, Object> producerProps =
KafkaTestUtils.producerProps(embeddedKafka);
ProducerFactory<Integer, String> pf =
new DefaultKafkaProducerFactory<>(producerProps);
KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf);
template.setDefaultTopic(TEMPLATE_TOPIC);
template.sendDefault("foo");
assertThat(records.poll(10, TimeUnit.SECONDS), hasValue("foo"));
template.sendDefault(0, 2, "bar");
ConsumerRecord<Integer, String> received = records.poll(10, TimeUnit.SECONDS);
assertThat(received, hasKey(2));
assertThat(received, hasPartition(0));
assertThat(received, hasValue("bar"));
template.send(TEMPLATE_TOPIC, 0, 2, "baz");
received = records.poll(10, TimeUnit.SECONDS);
assertThat(received, hasKey(2));
assertThat(received, hasPartition(0));
assertThat(received, hasValue("baz"));
}
}
前面的示例使用 Hamcrest 匹配器。
跟AssertJ
,最后一部分如下所示:
assertThat(records.poll(10, TimeUnit.SECONDS)).has(value("foo"));
template.sendDefault(0, 2, "bar");
ConsumerRecord<Integer, String> received = records.poll(10, TimeUnit.SECONDS);
// using individual assertions
assertThat(received).has(key(2));
assertThat(received).has(value("bar"));
assertThat(received).has(partition(0));
template.send(TEMPLATE_TOPIC, 0, 2, "baz");
received = records.poll(10, TimeUnit.SECONDS);
// using allOf()
assertThat(received).has(allOf(keyValue(2, "baz"), partition(0)));
模拟消费者和生产者
这kafka-clients
库提供MockConsumer
和MockProducer
用于测试目的的类。
如果您希望在某些测试中使用这些类,则带有侦听器容器或KafkaTemplate
分别,从 3.0.7 版本开始,该框架现在提供了MockConsumerFactory
和MockProducerFactory
实现。
这些工厂可以在侦听器容器和模板中使用,而不是默认工厂,默认工厂需要正在运行(或嵌入)代理。
下面是一个返回单个使用者的简单实现示例:
@Bean
ConsumerFactory<String, String> consumerFactory() {
MockConsumer<String, String> consumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST);
TopicPartition topicPartition0 = new TopicPartition("topic", 0);
List<TopicPartition> topicPartitions = Collections.singletonList(topicPartition0);
Map<TopicPartition, Long> beginningOffsets = topicPartitions.stream().collect(Collectors
.toMap(Function.identity(), tp -> 0L));
consumer.updateBeginningOffsets(beginningOffsets);
consumer.schedulePollTask(() -> {
consumer.addRecord(
new ConsumerRecord<>("topic", 0, 0L, 0L, TimestampType.NO_TIMESTAMP_TYPE, 0, 0, null, "test1",
new RecordHeaders(), Optional.empty()));
consumer.addRecord(
new ConsumerRecord<>("topic", 0, 1L, 0L, TimestampType.NO_TIMESTAMP_TYPE, 0, 0, null, "test2",
new RecordHeaders(), Optional.empty()));
});
return new MockConsumerFactory(() -> consumer);
}
如果您希望使用并发进行测试,则Supplier
工厂构造函数中的 lambda 每次都需要创建一个新实例。
使用MockProducerFactory
,有两个构造函数;一个用于创建一个简单的工厂,一个用于创建支持事务的工厂。
这里是例子:
@Bean
ProducerFactory<String, String> nonTransFactory() {
return new MockProducerFactory<>(() ->
new MockProducer<>(true, new StringSerializer(), new StringSerializer()));
}
@Bean
ProducerFactory<String, String> transFactory() {
MockProducer<String, String> mockProducer =
new MockProducer<>(true, new StringSerializer(), new StringSerializer());
mockProducer.initTransactions();
return new MockProducerFactory<String, String>((tx, id) -> mockProducer, "defaultTxId");
}
请注意,在第二种情况下,lambda 是BiFunction<Boolean, String>
其中,如果调用者想要事务性生产者,则第一个参数为 true;可选的第二个参数包含事务性 ID。这可以是默认值(如构造函数中提供),也可以被KafkaTransactionManager
(或KafkaTemplate
对于本地事务),如果已配置。如果您希望使用其他事务MockProducer
基于此值。
如果您在多线程环境中使用 producer,则BiFunction
应该返回多个生产者(可能使用ThreadLocal
).
事务MockProducer s 必须通过调用initTransaction() . |
使用MockProducer
,如果您不想在每次发送后关闭生产者,那么您可以提供自定义MockProducer
覆盖close
方法,该方法不调用close
方法。
当验证同一生产者上的多个发布而不关闭它时,这便于测试。
这是一个例子:
@Bean
MockProducer<String, String> mockProducer() {
return new MockProducer<>(false, new StringSerializer(), new StringSerializer()) {
@Override
public void close() {
}
};
}
@Bean
ProducerFactory<String, String> mockProducerFactory(MockProducer<String, String> mockProducer) {
return new MockProducerFactory<>(() -> mockProducer);
}