问题描述
当我尝试执行 mvn clean install
时,我只在一个平台上遇到了问题。作为构建的一部分,我们编译多个组件,最后我们使用wiremock 执行功能测试。它应该从功能测试配置文件中选择特定配置,并且应该从 application.properties 文件中选择默认属性。但出于某种原因,相同的代码无法找到这些文件中提到的属性。所以,只是想知道是否以某种方式,如果我可以获得在 wiremock 期间加载的属性文件列表?这将提供一些线索,说明为什么没有选择预期的属性文件?
src/main/resources
然后,从测试课开始。
@ContextConfiguration(classes = SampleFTConfiguration.class)
public class SampleControllerTest{
//test method
}
@ComponentScan("com.xxx.xxx.xxx.ft")
@PropertySource("classpath:application-test.properties")
public class SampleFTConfiguration{
}
注意:我不希望有人解决这个问题,我只想知道,如果我们能得到加载的属性文件的名称?
解决方法
好的,按照测试定义,请确保:
-
您应该使用 spring runner 运行测试(如果您使用的是 JUnit5,则使用 spring 扩展)。因此,您应该放置注释
@RunWith(SpringRunner.class)
(或@ExtendsWith(SpringExtension.class)
用于 junit 5) -
您使用的属性源是
application-test.properties
。您已经说过属性文件位于src/main/resources
但文件名可能暗示它应该位于src/test/resources
搜索并尝试了一段时间后,看起来 ConfigurableEnvironment
正是您要查找的内容。
代码非常简单。但是我认为最好直接调试和检查 configurableEnvironment
值,以便您可以根据需要调整代码(删除过滤器名称等)。
@Autowired
private ConfigurableEnvironment configurableEnvironment;
@Test
public void getProperties() {
Map<String,Object> mapOfProperties = configurableEnvironment.getPropertySources()
.stream()
.filter(propertySource -> propertySource.getName()
.contains("application-test.properties"))
.collect(Collectors.toMap(PropertySource::getName,PropertySource::getSource));
mapOfProperties.values()
.forEach(System.out::println);
}
代码会打印出来
{properties-one=value-for-properties-one,properties-two=value-for-properties-two}
使用我的 application-test.properties 值
properties-one=value-for-properties-one
properties-two=value-for-properties-two