【问题标题】:Bean not using test resources during testsBean 在测试期间不使用测试资源
【发布时间】: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 中同时定义 propertieslocations
  • @diginoise 回复了你的回答
  • 为什么它不会出现在src/main/resources 中?我假设您实际上是在运行时加载此文件。仅仅因为测试属性源正在更改并不意味着它期望资源的位置被保留以更改为测试资源。

标签: java spring spring-boot spring-boot-actuator


【解决方案1】:

试试这个:

@TestPropertySource(
    locations  = "classpath:test.properties",
    properties = {"filename=/test/some-file"} )

对于test.properties 放在src/test/resources

还请注意,位置可以是字符串数组,条目顺序定义优先级,properties 具有在locations 中找到的文件中定义的最高优先级覆盖属性。

【讨论】:

  • 它如何解决在 main/resources 中而不是在 test/resources 中查找“/test/some-file”文件的问题?这与属性无关,而与文件本身的查找位置有关。
  • @GreenFireman Spring 将寻找/test/some-file,因为这只是名为filename 的属性的属性值。然而,Spring 会寻找位于src/test/resources 中的属性文件test.properties
  • 重点是,在贡献者中,我正在读取属性中指定文件名的文件,即使在测试期间,它也试图从 main/resources 而不是 test/resources 读取它。文件,而不是属性!
猜你喜欢
  • 1970-01-01
  • 2013-12-27
  • 1970-01-01
  • 1970-01-01
  • 2016-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-10
相关资源
最近更新 更多