如何在spring boot中的每个测试类之后销毁和重新创建bean

Posted

技术标签:

【中文标题】如何在spring boot中的每个测试类之后销毁和重新创建bean【英文标题】:How to destroy and recreate bean after each test class in spring boot 【发布时间】:2017-04-19 20:45:56 【问题描述】:

我有一个应用程序,我创建 bean A 来安排配置中定义的任务,但在测试中我想在每个测试类之前创建它 bean 并在每个类之后销毁。

我需要它,因为我更新了每个类中的属性,例如:

@TestPropertySource(properties = ["my.property=valueForTest"])

在 JUnit/Spring 中可以吗?

【问题讨论】:

【参考方案1】:

我知道只有通过@DirtiesContext 丢弃整个上下文的选项。这显然也会丢掉你的豆子。

【讨论】:

@DirtiesContext 在这种情况下应该没问题,因为原始发布者无论如何都会为每个测试类创建一个全新的ApplicationContext(由于使用了@TestPropertySource)。 虽然我必须指出,为每个测试类创建一个新的ApplicationContext 实际上通常是最糟糕的做法

以上是关于如何在spring boot中的每个测试类之后销毁和重新创建bean的主要内容,如果未能解决你的问题,请参考以下文章