如何使用@TestPropertySource 在单元测试中覆盖@ConfigurationProperties 配置class 中使用的@PropertySource 的配置值
How to override config value from @PropertySource used in a @ConfigurationProperties config class in a unit test using @TestPropertySource
我有一个前缀为“assets”的配置属性实例。
@Configuration
@ConfigurationProperties( prefix = "assets", ignoreUnknownFields = true )
public class AssetsProperties
{
@NotNull
private Resource file;
public Resource getFile()
{
return file;
}
public void setFile( Resource file )
{
this.file = file;
}
}
其默认配置定义在:
@Configuration
@PropertySource( name = "assetsConfig", value = "classpath:com/package/boot/web/ui/assets/config/default-assets-config.properties" )
@Order( LOW_ORDER )
public class AssetsConfig
{
}
默认资产-config.properties 包含:
assets.file=classpath:assets.json
在我的单元测试中,我想使用以下方法覆盖默认值:
@TestPropertySource( locations = "classpath:com/package/boot/web/ui/assets/tests/assets-config.properties" )
资产-config.properties包含
assets.file=classpath:com/package/boot/web/ui/assets/tests/assets.json
遗憾的是,此值从未注入到 AssetsProperties 中。
我做错了什么,我不明白因为spring fmk ref doc says
Test property sources have higher precedence than those loaded from the operating system’s environment or Java system properties as well as property sources added by the application declaratively via @PropertySource or programmatically.
提前致谢,
帕斯科斯
您点击了 limitation in Spring Boot,这意味着它忽略了使用 @TestPropertySource
配置的属性文件。作为替代方案,您可以改为配置一个或多个内联属性:
@TestPropertySource(properties = "assets.file=classpath:com/package/boot/web/ui/assets/tests/assets.json")
我有一个前缀为“assets”的配置属性实例。
@Configuration
@ConfigurationProperties( prefix = "assets", ignoreUnknownFields = true )
public class AssetsProperties
{
@NotNull
private Resource file;
public Resource getFile()
{
return file;
}
public void setFile( Resource file )
{
this.file = file;
}
}
其默认配置定义在:
@Configuration
@PropertySource( name = "assetsConfig", value = "classpath:com/package/boot/web/ui/assets/config/default-assets-config.properties" )
@Order( LOW_ORDER )
public class AssetsConfig
{
}
默认资产-config.properties 包含:
assets.file=classpath:assets.json
在我的单元测试中,我想使用以下方法覆盖默认值:
@TestPropertySource( locations = "classpath:com/package/boot/web/ui/assets/tests/assets-config.properties" )
资产-config.properties包含
assets.file=classpath:com/package/boot/web/ui/assets/tests/assets.json
遗憾的是,此值从未注入到 AssetsProperties 中。 我做错了什么,我不明白因为spring fmk ref doc says
Test property sources have higher precedence than those loaded from the operating system’s environment or Java system properties as well as property sources added by the application declaratively via @PropertySource or programmatically.
提前致谢,
帕斯科斯
您点击了 limitation in Spring Boot,这意味着它忽略了使用 @TestPropertySource
配置的属性文件。作为替代方案,您可以改为配置一个或多个内联属性:
@TestPropertySource(properties = "assets.file=classpath:com/package/boot/web/ui/assets/tests/assets.json")