gpt4 book ai didi

java - Bean 在测试期间不使用测试资源

转载 作者:太空宇宙 更新时间:2023-11-04 11:06:47 25 4
gpt4 key购买 nike

我有一个 Spring Boot 应用程序,我通过扩展 InfoContributor 来扩展/monitoring/info 端点:

@Component
public class MyInfoContributor implements InfoContributor {

@Value("${filename}")
private String filename;

@Override
public void contribute(Builder builder) {
...
}

}

贡献者读取一个文件,该文件的名称是“filename”变量的值,并用其内容填充响应。

然后我对其实现了一项测试,将常用的属性值替换为特定于该测试的属性值:

@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 中指定)。我也尝试过使用测试配置文件的方法,结果是相同的。

是否可以让该组件在测试资源中查找文件?

最佳答案

试试这个:

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

test.properties放置在src/test/resources中。

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

关于java - Bean 在测试期间不使用测试资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46409009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com