1. EmbeddedKafkaRule vs. EmbeddedKafkaBroker
EmbeddedKafkaRule: A TestRule wrapper around an EmbeddedKafkaBroker.
查看源码,发现他俩都是创建一些虚拟的broker给test使用的。
然后看到这样一段话,不过对我没有什么用:
TopicAlreadyExists exceptions:
Some suggestions:
- Since you are using JUnit5, don’t use the JUnit4
EmbeddedKafkaRule
, useEmbeddedKafkaBroker
instead; or simply add@EmbeddedKafka
and the broker will be added as a bean to the Spring application context and its life cycle managed by Spring (use @DirtiesContext to destroy); for non-Spring tests, the broker will be created (and destroyed) by the JUnit5EmbeddedKafkaCondition
and is available viaEmbeddedKafkaCondition.getBroker()
. - Don’t use explicit ports; let the broker use its default random port and use embeddedKafka.getBrokersAsString() for the bootstrap servers property.
- If you must manage the brokers yourself (in @BeforeAll), destroy() them in @AfterAll
1.1 EmbeddedKafkaRule
官方文档: A JUnit 4 @Rule wrapper for the EmbeddedKafkaBroker is provided to create an embedded Kafka and an embedded Zookeeper server. (See @EmbeddedKafka Annotation for information about using @EmbeddedKafka with JUnit 5).
Starting with version 2.0, if you use Spring’s test application context caching, you can also declare a EmbeddedKafkaBroker bean, so a single broker can be used across multiple test classes. For convenience, we provide a test class-level annotation called @EmbeddedKafka to register the EmbeddedKafkaBroker bean. The following example shows how to use it:
@RunWith(SpringRunner.