2012-05-30 48 views
5

之前,我有一个主要的应用程序-context.xml中定义有两个位置的属性占位符:默认的属性文件和可选的覆盖文件:设置系统属性或环境变量属性的占位符与基于SpringJUnit4ClassRunner

<context:property-placeholder 
     location="classpath:config.properties,${configOverride}" 
     ignore-resource-not-found="true" /> 

可选覆盖位置允许仅指定应被覆盖的属性指定另一个属性文件(例如“-DconfigOverride = file:/home/app/config.properties”)。

对于我的单元测试,我使用的进口APP-context.xml的测试背景:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = {"classpath:test-context.xml"}) 
public class UserServiceTest { 
    ... 
} 

我如何可以设置应用程序上下文之前在应用程序内的系统属性或环境变量加载?我希望获得与在所有测试类中设置“-DconfigOverride = classpath:testConfig.properties”相同的效果,而不必指定命令行参数(如果可能)。的

回答

5

思考,

  1. 扩展SpringJUnit4ClassRunner和设置系统属性 configOverride在其构造函数/初始化块
  2. 然后通过ExtendedSpringJUnit4ClassRunner@RunWith
+0

感谢您的建议+1 - 我想过的是同样的事情,但在我去修改所有测试类之前,我想要检查在应用程序上下文中是否有任何事情可以做。我在测试上下文中重写了几个bean,但不幸的是,由于允许多个属性占位符,我无法重写该属性占位符。 – andy

3

这里是我落得这样做 - 我不必更改任何单元测试课程。不幸的是,我没有设置“configOverride”属性(参见AhamedMustafaM的答案),而是重写了原始属性占位符定义(在我尝试初始失败后再次尝试并使其工作)。

添加以下行到我的testContext.xml:

<!-- import the main app context --> 
<import resource="classpath:appContext.xml" /> 

<!-- this is the line i added --> 
<context:property-placeholder order="-999" 
     location="classpath:testConfig.properties" 
     ignore-unresolvable="true" /> 

注意顺序=“ - 999”的属性,它是用来保证在原产权占位符定义(一个或多个)的优先级。此外,我将“ignore-unresolvable”设置为“true”,以将任何无法解析的属性委托给原始占位符配置器。

+0

这是现货。对我有好处。 –

15

另一种替代方法是将环境属性设置为@BeforeClass注释方法,该方法将在上下文配置发生之前调用。

@BeforeClass 
public static void setSystemProps() { 
    System.setProperty("configOverride", "yourVal"); 
} 
+1

也许'@ AfterClass'中的'System.clearProperty(“configOverride”)' – vegemite4me

+0

抱歉,延迟响应。这绝对会起作用。我希望将测试类中唯一的硬编码字符串保留为弹簧上下文路径,但有时这是不可能的。 – andy

0

我的问题是类似的,但我想设置spring.profiles.active环境变量,原来,我只需要抛出@ActiveProfiles()与我想上测试本身的价值。