使用SpringJunit4ClassRunner在Property Placeholder之前设置系统属性或环境变量

and*_*ndy 6 java junit spring unit-testing properties

我有一个主app-context.xml,它定义了一个带有两个位置的属性占位符:default properties file和一个可选的覆盖文件:

<context:property-placeholder
        location="classpath:config.properties,${configOverride}"
        ignore-resource-not-found="true" />
Run Code Online (Sandbox Code Playgroud)

可选的覆盖位置允许指定另一个属性文件(例如"-DconfigOverride = file:/home/app/config.properties"),其中只包含应该被覆盖的属性.

对于我的单元测试,我使用的是导入app-context.xml的测试上下文:

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

如何在加载应用程序上下文之前在应用程序中设置系统属性或环境变量?我希望实现与在所有测试类中设置"-DconfigOverride = classpath:testConfig.properties"相同的效果,而不必在可能的情况下指定命令行arg.

kev*_*vin 15

另一种方法是在@BeforeClass带注释的方法中设置environment属性,该方法将在上下文配置发生之前调用.

@BeforeClass
public static void setSystemProps() {
    System.setProperty("configOverride", "yourVal");
}
Run Code Online (Sandbox Code Playgroud)


Aha*_*a M 5

思考,

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