【发布时间】:2018-07-14 11:48:05
【问题描述】:
我正在尝试覆盖在测试类中具有默认值的 Spring @Value 注释属性。
@Configuration
public class MyConfig {
@Value("${MAX_CONN:200}")
private int maxConn;
//more code here
}
@RunWith(SpringRunner.class)
@ContextConfiguration(classes={MyConfig.class, PropertySourcesPlaceholderConfigurer.class}, loader=AnnotationConfigContextLoader.class)
@TestPropertySource(properties = {
"MAX_CONN=2"
})
public class SomeTest {
//tests here
}
我为此目的使用了org.springframework.test.context.TestPropertySource 注释(thanks for the advise)。在调试过程中,我看到 maxConn 值仍然是 200。如果从原始代码 @Value("${MAX_CONN}") 中删除默认值,则 maxConn 值被 2 覆盖。
也可以通过定义环境变量来覆盖默认属性。
我想知道是否有办法覆盖具有默认值的@Value 注释属性?
注意:Spring 版本 - 4.3.13
【问题讨论】:
-
你可以使用
ReflectionTestUtils.setField() -
@pvpkiran - 谢谢,我也是从link 学到的。我只是想知道是否有更优雅的方式。
-
对于
unit test,您不必初始化 Spring,以防您不进行测试。 Spring 特定:如数据库工作或 MVC。 -
@oleg.cherednik - 最后,使用 Mockito 和 ReflectionTestUtils 实现“无弹簧”单元测试。更多的代码,更少的时间,没有巫术
-
@anuta 但它在大型项目中节省了大量时间,Spring 团队在他们的文档中推荐了这种方法。
标签: java spring unit-testing