This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Problem: Populating properties of the Spring @Value flag in unit tests

I tried to write a unit test for a simple bean that is used to validate forms in my program. The bean is annotated with @Component and has a class variable initialized as such

@Value("${this.property.value}") private String this.property;

I want to write unit tests for the validation methods in this class, but, if possible, I want to complete the tests without using properties files. The reason I do this is that if the value I get from the properties file changes, I hope it won’t affect my test case. My test case tests the code that validates the method, not the value itself.

Is there a way to initialize a Java class using Java code in my test class, populate the class with properties of the Spring @Value annotation, and then test with that property?

I do find this How to seems close to the mark, but still use a properties file. I want to use Java code.

answer

If possible, I’ll try to write these tests without a Spring Context. If you create this class in a test without Spring, you have full control over its properties.

To set the @Value property, you can use Springs ReflectionTestUtils – it has a method setField to set the private property.

@see JavaDoc: ReflectionTestUtils.setField(java.lang.Object, java.lang.String, java.lang.Object)

Answer two

This seems to work, though it’s still a bit wordy (I still want shorter ones)

@BeforeClass
public static void beforeClass(a) {
    System.setProperty("some.property"."<value>");
}

// Optionally:
@AfterClass
public static void afterClass(a) {
    System.clearProperty("some.property");
Copy the code

The article translated from Stack Overflow:stackoverflow.com/questions/1…