Populating Spring @Value during Unit Test

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.

11 Answers
11

Leave a Comment