spring启动测试在测试中不使用重写bean,尽管标记为@primary

zfciruhq  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(276)

我们有一个豆子公司的处理器。在SpringBootIntegrationTest中,我们想测试一个异常场景,当这个bean中的一个方法抛出异常时。
因此,我们创建了一个覆盖bean testcompanyprocessor,它扩展了companyprocessor。testcompanyprocessor被标记为@primary。当我们只运行这个测试类时,测试运行良好,并且重写的bean按预期使用。
但是这个测试类和其他几个测试类一起运行,每个测试类都标记为@springboottest,我们看到这个测试在第一个示例失败,因为它没有使用重写的bean,而是使用这个原始bean。我们有自动重试失败最多3次。在第二次或第三次重试时,它会以某种方式找到正确的重写主bean并通过测试。
有什么原因吗?为什么它在第一个示例中找到原始bean,然后在随后的重试中找到正确的重写bean,然后与其他几个测试类一起运行。
重写的bean定义如下。

@Primary
@Component
@ConditionalOnExpression("'${test.company.processor}' == 'true'")
class TestCompanyProcessor

在我们的测试课上

@TestPropertySource(properties = {"test.company.processor=true"})
class TestCompanyProcessorTest {

}

p、 当我们使用@mockbean注解时,我们看到了相同的行为

bjp0bcyl

bjp0bcyl1#

如果您有多个共享同一上下文的spring测试,您可能会看到这种行为。
spring正在测试之间缓存测试应用程序上下文。这是默认行为,因为在spring上下文中示例化对象可能需要一些时间。
如果在不同的测试中有不同的bean,那么应该用@dirtiescontext注解标记更改applicationcontext的测试(比如testcompanyprocessortest类)。
有关缓存的详细信息:
https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html#testing-ctx管理
dirtiescontext示例:
https://www.baeldung.com/spring-dirtiescontext

相关问题