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

新手上路,请多包涵

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

 @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
public class TestWarSpringContext { ... }

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

原文由 Hans-Peter Störr 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

您可以在静态初始化程序中初始化 System 属性:

 @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
public class TestWarSpringContext {

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

}

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

原文由 Jimmy Praet 发布,翻译遵循 CC BY-SA 3.0 许可协议

从 Spring 4.1 开始,正确的方法是使用 @TestPropertySource 注释。

 @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
    ...
}

请参阅 Spring 文档Javadocs 中的 @TestPropertySource

原文由 Raman 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏