事实证明,最好的方法(直到Spring修复此监督)是一种
PropertySourcesPlaceholderConfigurer将引入
test.properties(或任何你想要的东西)@import或扩展它的方法
@Configuration。
import org.apache.commons.lang3.ArrayUtils;import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import java.io.IOException;@Configurationpublic class PropertyTestConfiguration { @Bean public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() throws IOException { final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); ppc.setLocations(ArrayUtils.addAll( new PathMatchingResourcePatternResolver().getResources("classpath*:application.properties"), new PathMatchingResourcePatternResolver().getResources("classpath*:test.properties") ) ); return ppc; }}这使你可以在application.properties中定义默认值,并在test.properties中覆盖它们。当然,如果你有多个方案,则可以
PropertyTestConfiguration根据需要配置该类。
并在单元测试中使用它。
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(loader = AnnotationConfigContextLoader.class)public class PropertyTests { @Value("${elastic.index}") String index; @Configuration @import({PropertyTestConfiguration.class}) static class ContextConfiguration { }}


