Spring启动-测试-为bean拆卸

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

我使用@EmbeddedKafka注释来制作kafka模拟:

@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注释将无法工作
我想我可以从一个测试中将bean转换成一个静态字段,然后在tearDown()中使用它,但这真的很难看

在所有测试完成后只关闭bean一次的“良好实践”是什么

@AfterAll方法只能是静态的

那不是真的

从:

表示带注释的方法应在当前类中的所有@Test、@RepeatedTest、@parameteredtest和@TestFactory方法之后执行;类似于JUnit4的@AfterClass。这些方法是继承的(除非它们被隐藏或重写),并且必须是静态的(除非使用“每类”测试实例生命周期)

如果使用
@TestInstance(Lifecycle.PER_CLASS)
,那么
@方法可以是非静态的。这也记录在以下文件中:

“每类”模式比默认的“每方法”模式有一些额外的好处。具体来说,使用“每类”模式,可以在非静态方法以及接口默认方法上声明@BeforeAll和@AfterAll


可能会有帮助:您是否尝试过使用
@ClassRule
创建嵌入式卡夫卡,而不是自动连接
@Autowired
嵌入式卡夫卡?