在单元测试期间填充 Spring @Value [英] Populating Spring @Value during Unit Test
问题描述
我正在尝试为我的程序中用于验证表单的简单 bean 编写单元测试.bean 使用 @Component
进行注释,并具有使用
I'm trying to write a Unit Test for a simple bean that's used in my program to validate forms. The bean is annotated with @Component
and has a class variable that is initialized using
@Value("${this.property.value}") private String thisProperty;
我想为这个类中的验证方法编写单元测试,但是,如果可能的话,我不想使用属性文件.这背后的原因是,如果我从属性文件中提取的值发生变化,我希望这不会影响我的测试用例.我的测试用例正在测试验证值的代码,而不是值本身.
I would like to write unit tests for the validation methods inside this class, however, if possible I would like to do so without utilizing the properties file. My reasoning behind this, is that if the value I'm pulling from the properties file changes, I would like that to not affect my test case. My test case is testing the code that validates the value, not the value itself.
有没有办法在我的测试类中使用 Java 代码来初始化一个 Java 类并在该类中填充 Spring @Value 属性,然后使用它进行测试?
Is there a way to use Java code inside my test class to initialize a Java class and populate the Spring @Value property inside that class then use that to test with?
我确实发现这个 How To 似乎很接近,但仍然使用属性文件.我宁愿这都是 Java 代码.
I did find this How To that seems to be close, but still uses a properties file. I would rather it all be Java code.
推荐答案
如果可能的话,我会尝试在没有 Spring Context 的情况下编写这些测试.如果你在没有 spring 的测试中创建这个类,那么你可以完全控制它的字段.
If possible I would try to write those test without Spring Context. If you create this class in your test without spring, then you have full control over its fields.
要设置 @value
字段,您可以使用 Springs ReflectionTestUtils
- 它有一个方法 setField
设置私有字段.
To set the @value
field you can use Springs ReflectionTestUtils
- it has a method setField
to set private fields.
@see JavaDoc: ReflectionTestUtils.setField(java.lang.Object, java.lang.String, java.lang.Object)
这篇关于在单元测试期间填充 Spring @Value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!