【发布时间】:2017-09-25 15:35:03
【问题描述】:
我有一个 Spring Boot 应用程序,我通过扩展 InfoContributor 扩展了 /monitoring/info 端点:
@Component
public class MyInfoContributor implements InfoContributor {
@Value("${filename}")
private String filename;
@Override
public void contribute(Builder builder) {
...
}
}
贡献者读取一个文件,该文件的名称是“文件名”变量的值,并用它的内容填充响应。
然后我为它实现了一个测试,我用这个测试特定的属性值替换了通常的属性值:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(properties = {
"filename=/test/some-file"
})
public class MyInfoContributorTest {
@Autowired
protected MockMvc mvc;
@Test
public void shouldReturnBuildInfo() throws Exception {
mvc.perform(get("/monitoring/info"))
.andExpect(content().string("..."))
.andExpect(status().isOk());
}
}
测试有效,但有一个问题:它在 main/resources 而不是 test/resources 中寻找这个“/test/some-file”文件(在 TestPropertySource 中指定)。 我也尝试了使用测试配置文件的方法,结果是一样的。
是否可以让这个组件在测试资源中查找文件?
【问题讨论】:
-
不应该是classpath:some-file吗?
-
为什么?该属性包含文件的名称,如果我在该注释中指定现有文件,则可以正确找到并读取它。问题是它在主资源中找,我需要它在测试资源中找
-
您是否尝试在
@TestPropertySource中同时定义properties和locations? -
@diginoise 回复了你的回答
-
为什么它不会出现在
src/main/resources中?我假设您实际上是在运行时加载此文件。仅仅因为测试属性源正在更改并不意味着它期望资源的位置被保留以更改为测试资源。
标签: java spring spring-boot spring-boot-actuator