I have a bean with some private String fields that get set from the application context yaml file of my SpringBoot application. These variables are used in some of the public functional methods of the bean, and would get initialized on server startup of my spring boot application. I need these to be initialized during my tests as I need to add tests to ensure that these fields are getting used correctly in my code. How would I do that?
In the test when I had instantiated the bean class I want to test , these private string fields were null, and these are not accessible in the test directly. I did not want to change the visibility of the fields, or add public methods just for this purpose.
The other option would be to directly use java Reflection API, but that would amount to some complicated cryptic code.
The solution I adopted was to use the reflection utility class that Spring framework provides
import org.springframework.test.util.ReflectionTestUtils;
ReflectionTestUtils.setField(myInstance, "my-field-one", "my-value-one");
Helpful when you need it.