I have a ConfigurationProperties class and want to test it with 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;
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(); } }
java spring spring-test junit
membersound
source share