Spring 使用多个 属性 文件启动 JUnit 和 @TestPropertySource

Spring Boot JUnit and @TestPropertySource using multiple property files

Spring 启动 2.0.3.RELEASE

有多个属性文件要处理.. application.properties 和 application-DEV.properties

在 Junit 测试中使用注解 @TestPropertySource 我只能让它读取一个文件:

@TestPropertySource("file:C:\Users\user\eclipse-workspace\one2one_httpCall\src\main\resources\application-DEV.properties")

按预期工作

但是我需要两个属性文件我确实看到了位置选项但没有看到一个以上文件的示例.. 尝试了不同的选项但 none 有效:

@TestPropertySource(locations = "classpath:application-DEV.properties;classpath:application.properties")

尝试了几种我没有发布的方法,甚至尝试使用@TestPropertySource 两次,但错误提示您不能使用它两次。

尝试使用@PropertySource,因为你可以使用它两次但没有用,因为这是一个 Junit 测试。查看了一堆关于 stacktrace + 其他人的问题并尝试但没有运气。

所以我的问题是如何通过@TestPropertySource 注释使用两个属性文件?

如果查看 @TestPropertySource 的定义,您会发现 locationsString [] 类型。因此,如果你需要给它传递多个值,你必须用数组来传递:

@TestPropertySource(locations = { "classpath:application.properties", "classpath:application-DEV.properties" })

另外,请注意声明属性文件的顺序。如 TestPropertySource docs 中所述:

Each location will be added to the enclosing Environment as its own property source, in the order declared.

所以您可能希望在之后声明您的 DEV 属性,以避免它们被您的生产属性覆盖。