I have a ConfigurationProperties
class and want to test it using junit
. But the object is always null
. What might be missing in the following code?
@EnableAutoConfiguration
@ComponentScan
@EnableConfigurationProperties(MyProperties.class)
public class AppConfig {
}
@Service
public class MyService {
@Autowired
private MyProperties props;
public void run() {
props.getName();
}
}
@Component
@ConfigurationProperties(prefix = "my")
public class MyProperties {
private String name;
//getter,setter
}
application.properties:
my.name=test
test:
@Configuration
@ComponentScan(basePackageClasses = {MyService.class, MyProperties.class},
includeFilters = @ComponentScan.Filter(value = {MyService.class, MyProperties.class},
type = FilterType.ASSIGNABLE_TYPE),
lazyInit = true
)
@PropertySources(
@PropertySource("application.properties")
)
class AppTest {
@Bean
public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
return new PropertySourcesPlaceholderConfigurer();
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationConfigTest.class)
public class MyTest extends AbstractJUnit4SpringContextTests {
@Autowired
private MyService service;
@Test
public void testService() {
service.run();
}
}
We use @Configuration so that Spring creates a Spring bean in the application context. @ConfigurationProperties works best with hierarchical properties that all have the same prefix; therefore, we add a prefix of mail.
You can use @TestPropertySource annotation in your test class. Just annotate @TestPropertySource("classpath:config/mailing. properties") on your test class. You should be able to read out the property for example with the @Value annotation.
At its core, the TestContext framework allows you to annotate test classes with @ContextConfiguration to specify which configuration files to use to load the ApplicationContext for your test.
The following will load it for you:
@ContextConfiguration(classes = Application.class, initializers = ConfigFileApplicationContextInitializer.class)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With