我想在多个环境中运行我的测试套件,如下所示:
ApplicationContextTest.class
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/application-context.xml")
public class MyTest{
@Autowired
private ApplicationContext applicationContext;
@Test
public void test1() {
((ConfigurableEnvironment)applicationContext.getEnvironment()).setActiveProfiles("env1");
((GenericXmlApplicationContext)applicationContext).refresh();
}
@Test
public void test2() {
((ConfigurableEnvironment)applicationContext.getEnvironment()).setActiveProfiles("env2");
((GenericXmlApplicationContext)applicationContext).refresh();
}
}
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<beans profile="env1">
</beans>
<beans profile="env2">
</beans>
当我运行测试时,出现异常
原因:java.lang.IllegalStateException:GenericApplicationContext不支持多次刷新尝试:只需调用“刷新”一次
ApplicationContext启动后有没有办法设置Active Profile?
或者有什么解决方案可以解决上述异常吗?
谢谢。
最佳答案
选择一个或多个特定配置文件的正常方法是在运行测试时设置系统属性
-Dspring.profiles.active=env1
您还可以使用系统属性将一个或多个配置文件设置为默认配置
-Dspring.profiles.default=env1
我通常在测试的静态 init 方法中执行此操作
@BeforeClass
public static void init() {
// set default spring test profile
System.setProperty("spring.profiles.default", "default");
}
如果搜索这些属性,您将找到一些信息(如果您需要 Spring 代码引用,则必须查看 AbstractEnvironment 类)。
我不知道如何在启动后更改配置文件。在这种情况下,您可能必须在每个测试中使用新的 JVM(例如,可以通过使用 reuseForks 设置的 Maven Surefire 插件来完成)。或者甚至更好地将使用相同配置文件的测试放在同一个测试类中,并根据需要设置配置文件。
恕我直言,测试不应依赖于特定的配置文件。无论使用什么配置文件,测试都应该通过。您可以轻松更改,例如在测试(模拟)或“真实”环境之间。
关于spring - 在多个环境中运行测试套件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18543670/