首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在春季测试中设置环境变量或系统属性?

如何在春季测试中设置环境变量或系统属性?
EN

Stack Overflow用户
提问于 2012-07-03 08:16:06
回答 10查看 235.2K关注 0票数 124

我想编写一些测试来检查已部署的WAR的XML配置。不幸的是,有些bean要求设置一些环境变量或系统属性。当使用@ContextConfiguration使用方便的测试样式时,如何在初始化spring之前设置一个环境变量?

代码语言:javascript
复制
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
public class TestWarSpringContext { ... }

如果我用注释配置应用程序上下文,我看不到在初始化spring上下文之前可以做一些事情的钩子。

EN

回答 10

Stack Overflow用户

回答已采纳

发布于 2012-08-27 14:48:17

可以在静态初始化器中初始化系统属性:

代码语言:javascript
复制
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
public class TestWarSpringContext {

    static {
        System.setProperty("myproperty", "foo");
    }

}

静态初始化程序代码将在初始化spring应用程序上下文之前执行。

票数 155
EN

Stack Overflow用户

发布于 2016-03-03 04:45:23

从Spring4.1开始,正确的方法是使用@TestPropertySource注释。

代码语言:javascript
复制
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
    ...    
}

参见@TestPropertySource中的春季医生爪哇

票数 117
EN

Stack Overflow用户

发布于 2016-12-23 17:21:31

还可以使用测试ApplicationContextInitializer来初始化系统属性:

代码语言:javascript
复制
public class TestApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>
{
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext)
    {
        System.setProperty("myproperty", "value");
    }
}

然后,除了Spring上下文配置文件位置之外,还在测试类上配置它:

代码语言:javascript
复制
@ContextConfiguration(initializers = TestApplicationContextInitializer.class, locations = "classpath:whereever/context.xml", ...)
@RunWith(SpringJUnit4ClassRunner.class)
public class SomeTest
{
...
}

这样,如果应该为所有单元测试设置特定的系统属性,则可以避免代码重复。

票数 18
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11306951

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档