我有一个ConfigurationProperties
课程,想要使用junit
进行测试。但对象总是null
。以下代码中可能缺少什么?
@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
试验:
@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();
}
}
答案 0 :(得分:10)
以下内容将为您加载:
@ContextConfiguration(classes = Application.class, initializers = ConfigFileApplicationContextInitializer.class)