I want to test small parts of the application that rely on properties loaded with @Autowired and @ConfigurationProperties. I am looking for a solut
If you use Spring Boot, now you only need:
@RunWith(SpringRunner.class)
@SpringBootTest
No extra @ContextConfiguration, no extra class only for tests to EnableAutoConfiguration and EnableConfigurationProperties. You don't have to specify the configuration class to load, they will all be loaded.
But, ensure the properties entries you want to read in main/resources/application.yml is also present in test/resources/application.yml. Repetition is unavoidable.
Another way is:
MyApplicationTest.java, at the same level. This class can be empty.Like:
@EnableAutoConfiguration
@EnableConfigurationProperties(value = {
ConnectionPoolConfig.class
})
public class MyApplicationTestConfiguration {
}
Like:
@RunWith(SpringRunner.class)
//@SpringBootTest // the first, easy way
@ContextConfiguration(classes = MyApplicationTestConfiguration.class,
initializers = ConfigFileApplicationContextInitializer.class)
public class ConnectionPoolConfigTest {
@Autowired
private ConnectionPoolConfig config;
Basically, you:
@EnableConfigurationProperties and @EnableAutoConfiguration, listing all the @ConfigurationProperties files you want to loadapplication.yml file.And, put the values to load in test/resources/application.yml. Repetition is unavoidable. If you need load another file, use @TestProperties() with a location. Note: @TestProperties only supports .properties files.
Both way works for configuration class loading values
application.yml/application.propertiesPropertySource, like @PropertySource(value = "classpath:threadpool.properties")Last notes from Spring doc, as per here
Some people use Project Lombok to add getters and setters automatically. Make sure that Lombok does not generate any particular constructor for such a type, as it is used automatically by the container to instantiate the object.
Finally, only standard Java Bean properties are considered and binding on static properties is not supported.
That means, if you have lombok.@Builder without @NoArgsConstructor nor @AllArgsConstructor, properties injection will not happen because it only sees the invisible constructor created by @Builder. So, be sure to use none, or all of these annotations!