Spring启动-测试-为bean拆卸
我使用@EmbeddedKafka注释来制作kafka模拟:Spring启动-测试-为bean拆卸,spring,spring-boot,junit,junit5,spring-boot-test,Spring,Spring Boot,Junit,Junit5,Spring Boot Test,我使用@EmbeddedKafka注释来制作kafka模拟: @ExtendWith(SpringExtension.class) @SpringBootTest @EmbeddedKafka(partitions = 1, topics = {"topic"}, brokerProperties = { "auto.create.topics.enable=${topics.autoCreate:false}", "delete.topic.en
@ExtendWith(SpringExtension.class)
@SpringBootTest
@EmbeddedKafka(partitions = 1,
topics = {"topic"},
brokerProperties = {
"auto.create.topics.enable=${topics.autoCreate:false}",
"delete.topic.enable=${topic.delete:true}",
"broker.id=2"})
public class KafkaUsersTest {
@Autowired
private EmbeddedKafkaBroker embeddedKafka;
@Test
public void test1() {
// test something
}
@Test
public void test2() {
// test something
}
...
}
现在,在测试完成后,我想关闭嵌入的Kafka bean。大概是这样的:
@AfterAll
public void tearDown(){
embeddedKafka.getKafkaServers().forEach(KafkaServer::shutdown);
embeddedKafka.getKafkaServers().forEach(KafkaServer::awaitShutdown);
}
问题是:
- @AfterAll方法只能是静态的
- 如果我将其设置为静态,那么嵌入的卡夫卡也必须是静态的,那么@Autowired注释将无法工作
@TestInstance(Lifecycle.PER_CLASS)
,那么@方法可以是非静态的。这也记录在以下文件中:
“每类”模式比默认的“每方法”模式有一些额外的好处。具体来说,使用“每类”模式,可以在非静态方法以及接口默认方法上声明@BeforeAll和@AfterAll
可能会有帮助:您是否尝试过使用@ClassRule
创建嵌入式卡夫卡,而不是自动连接@Autowired
嵌入式卡夫卡?