我需要在测试类的一个方法中更改应用程序上下文中激活的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对我来说不起作用,因为它是在类/方法执行之后运行的,而不是之前,而且我需要在刷新/重新加载之前执行一行代码。
有什么建议吗?我尝试浏览正在运行的监听器/钩子,但是我没有看到一个明显的位置可以插入自己来实现这种行为。
AbstractGenericWebContextLoader.customizeContext
提供的内容,其中包括GenericWebApplicationContext
和WebMergedContextConfiguration
。我没有看到任何设置配置文件的方法,您能给我指点一下吗? - David EGenericWebApplicationContext
上,您可以调用context.getEnvironment().setActiveProfiles(...)
等方法。 - Sam BrannenSmartContextLoader
实现的示例,您可以在Google上搜索“implements SmartContextLoader”(包括引号),但这不会返回太多结果,因为大多数人要么扩展AbstractContextLoader
或AbstractGenericContextLoader
。例如,Spring Boot引入了自己的SpringApplicationContextLoader
,它直接扩展了AbstractContextLoader
。 - Sam Brannen