Issue
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.
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?
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.
Solution
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.
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)
Answered By - Ralph
Answer Checked By - Mildred Charles (JavaFixing Admin)