因此,在这个主题上有很多热门话题,但没有一个对我有用。
我有一个非常简单的配置类:
@Configuration
@ConfigurationProperties(prefix = "props")
public class TagIncluder {
private static final String PARAMETER_NAME = "tags";
private List<String> tags;
public TagIncluder() {
tags = new ArrayList<>();
}
public List<String> getTags() {
return tags;
}
@Handler
public void attachIncludedTags(Exchange exchange) {
exchange.getIn().setHeader(PARAMETER_NAME, tags);
}
}
我希望此类能够加载不同的属性文件。我正在使用yaml,文件名为application-tag_test.yml
。我试图把在该文件中src/main/resources
,src/test/resources
并且src/test/resources/config
,但是它永远不会回升。
这是属性文件的内容:
props:
tags:
- test
最后,测试用例:
@SpringBootTest
@ActiveProfiles("tag_test")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TagIncluder.class)
public class TagIncluderTest extends ExchangeTestSupport {
@Autowired
private TagIncluder sut;
@Test
public void attachIncludedTags_shouldUseTagsInFileIfFileSpecified() {
Exchange testExchange = createExchange();
sut.attachIncludedTags(testExchange);
Assertions.assertThat(testExchange.getIn().getHeader("tags", List.class))
.size().isGreaterThanOrEqualTo(1);
}
}
此外,我尝试将application.properties
文件放置在上述位置,内容如下:
spring.profiles.active=tag_test
Spring将我的yaml文件设置为被测类的所需配置是什么?
更新
因此,经过一番探索和反复试验,我发现以下工作原理:
@SpringBootTest
@ActiveProfiles("tag_test")
@RunWith(SpringJUnit4ClassRunner.class)
public class TagIncluderTest extends ExchangeTestSupport {
@Autowired
private TagIncluder sut;
@Test
public void attachIncludedTags_shouldUseTagsInFileIfFileSpecified() {
Exchange testExchange = createExchange();
sut.attachIncludedTags(testExchange);
Assertions.assertThat(testExchange.getIn().getHeader("tags", List.class))
.size().isGreaterThanOrEqualTo(1);
}
}
这里的区别在于,我已经删除了@ContextConfiguration
注释,而让Spring处理了所有这些注释。
这要慢很多,我希望指定需要的东西。我认为这种情况将来可能会中断,例如,如果我添加另一个将从整个上下文开始的配置类并抛出错误,因为这些属性未包含在我的application-tag_test.yml
配置中。
最后,我尝试进行配置的上述任何位置均适用于以上注释。该application.properties
指定不需要配置文件。
如果有人知道的方式来指定哪些应该被装入的背景下,而不是,我是另一种解决方案非常感激。
Spring Boot Test文档指出
External properties, logging, and other features of Spring Boot are installed in the context by default only if you use SpringApplication to create it.
这意味着您需要有一个运行中的Spring Boot应用程序,才能测试与测试用例中的属性加载相关的任何东西。
同样,从属性设置列表需要一个setter。这有效:
@Configuration
@ConfigurationProperties(prefix = "props")
public class TagIncluder {
private List<String> tags;
public void setTags(List<String> tags) {
this.tags = tags;
}
public List<String> getTags() {
return tags;
}
}
@Component
public class MyComponent {
@Autowired
TagIncluder tagIncluder;
}
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@SpringBootTest
@ActiveProfiles("tag_test")
@RunWith(SpringRunner.class)
public class TagIncluderTest {
@Autowired
private TagIncluder sut;
@Test
public void attachIncludedTags_shouldUseTagsInFileIfFileSpecified() {
System.out.println(sut.getTags());
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句