Scenario
我有一个 Spring Boot 应用程序@Configuration
带注释的 Spring 配置类,其中包含一些@Value
带注释的字段。为了进行测试,我想用自定义测试值替换这些字段值。
不幸的是,这些测试值不能使用简单的属性文件、(字符串)常量或类似文件来覆盖,而是我must使用一些自定义编写的属性来解析 Java 类(例如TargetProperties.getProperty("some.username")
).
我遇到的问题是当我添加自定义PropertySource
to the ConfigurableEnvironment
在我的测试配置中,已经太晚了,因为这PropertySource
将被添加after例如RestTemplate
已经被创造了。
Question
我怎样才能覆盖@Value
带注释的字段within a @Configuration
获得属性的类以编程方式通过自定义 Java 代码before还有其他东西被初始化吗?
Code
生产配置类
@Configuration
public class SomeConfiguration {
@Value("${some.username}")
private String someUsername;
@Value("${some.password}")
private String somePassword;
@Bean
public RestTemplate someRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add(
new BasicAuthorizationInterceptor(someUsername, somePassword));
return restTemplate;
}
}
测试配置类
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class SomeTest {
@SpringBootConfiguration
@Import({MySpringBootApp.class, SomeConfiguration.class})
static class TestConfiguration {
@Autowired
private ConfigurableEnvironment configurableEnvironment;
// This doesn't work:
@Bean
@Lazy(false)
// I also tried a @PostConstruct method
public TargetPropertiesPropertySource targetPropertiesPropertySource() {
TargetPropertiesPropertySource customPropertySource =
new TargetPropertiesPropertySource();
configurableEnvironment.getPropertySources().addFirst(customPropertySource);
return customPropertySource;
}
}
}
您可以直接在@SpringBootTest
注释使用properties
范围:
@SpringBootTest(properties = {"some.username=user", "some.password=pwd"},
webEnvironment = SpringBootTest.WebEnvironment.NONE)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)