gpt4 book ai didi

java - 在测试方法中重新加载或刷新 Spring 应用程序上下文?

转载 作者:IT老高 更新时间:2023-10-28 13:59:20 42 4
gpt4 key购买 nike

我需要在我的测试类的单个方法中更改在我的 applicationContext 中处于 Activity 状态的 Spring 配置文件,为此我需要在刷新比赛之前运行一行代码,因为我使用的是 ProfileResolver。我尝试了以下方法:

@WebAppConfiguration
@ContextConfiguration(locations = {"/web/WEB-INF/spring.xml"})
@ActiveProfiles(resolver = BaseActiveProfilesResolverTest.class)
public class ControllerTest extends AbstractTestNGSpringContextTests {
@Test
public void test() throws Exception {
codeToSetActiveProfiles(...);
((ConfigurableApplicationContext)this.applicationContext).refresh();
... tests here ...
codeToSetActiveProfiles(... back to prior profiles ...);
... ideally refresh/reload the context for future tests
}
}

但我明白了:

java.lang.IllegalStateException: GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once

DirtiesContext 对我不起作用,因为它是在类/方法执行之后而不是之前运行的,而且无论如何我都需要在运行刷新/重新加载之前执行一行代码。

有什么建议吗?我试图查看正在运行的监听器/ Hook ,但我没有看到明显的位置可以插入自己以实现此行为。

最佳答案

根据设计,ApplicationContext 的编程刷新不受 Spring TestContext 框架的明确支持。此外,测试方法并不打算刷新上下文。

因此,我建议您重新评估是否需要进行刷新,并考虑替代方法,例如将需要一组不同的 Activity 配置文件的测试方法放在专用的测试类中。

综上所述,@ActiveProfiles 支持 declarative 配置(通过 valueprofiles 属性)和 用于测试的 Activity 配置文件的程序化配置(通过 resolver 属性),但仅限于测试类级别(而不是方法级别)。另一种选择是实现 ApplicationContextInitializer 并通过 @ContextConfiguration(initializers=...) 进行配置。

影响 ApplicationContext before 刷新的唯一其他方法是实现 SmartContextLoader 或扩展提供的类之一并配置它通过 @ContextConfiguration(loader=...)。例如,AbstractGenericContextLoader.customizeContext() 允许“自定义由加载器创建的 GenericApplicationContext bean 定义已加载到上下文中,但之前上下文被刷新。”

最好的问候,

Sam(Spring TestContext 框架的作者)

关于java - 在测试方法中重新加载或刷新 Spring 应用程序上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24720330/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com