java - Springboot集成测试:在bean初始化之前用pwd更新application.yml属性
问题描述
我正在编写 Springboot 集成测试。在 src/test/resources 中有一个 application.yml。yml中有一个属性:
testFilePath: "projectBaseDirectoryPathVariable/src/test/resources/testFiles"
测试中使用的 bean 必须在 bean(类)构造函数中读取此值“testFilePath”。
在执行集成测试之前,我希望能够将 的值替换为projectBaseDirectoryPathVariable
用户目录(或 PWD 路径)。这样,bean 初始化具有正确的完整路径,即/users/usrname/projects/project_name/src/test/resources/testFiles
我尝试使用BeforeAll() 方法,该方法将替换 application.yml 文件内容,因此将 projectBaseDirectoryPathVariable 替换为完整路径。但是bean(类)仅在调用其构造函数时才使用旧值“projectBaseDirectoryPathVariable”。
有什么办法可以处理这种情况?
这是测试:
@Slf4j
@ActiveProfiles({"test", "master"})
@SpringBootTest
public class MyIntegrationTest {
@Autowired
ClassUsingApplicationYml classUsingApplicationYml;
@BeforeAll
static void beforeAll() throws IOException {
//Some code
}
@Test
void dummyClassTest() {
// Some code
}
}
ClassUsingApplicationYml/bean.
@Slf4j
@Component
public class ClassUsingApplicationYml implements Tasklet {
public ClassUsingApplicationYml(@Value("${file.results}") String resultsDirectory) {
//resultsDirectory should get "/users/usrname/projects/project_name/src/test/resources/testFiles",
//but it is getting "projectBaseDirectoryPathVariable/src/test/resources/testFiles"
this.resultsDirectory = resultsDirectory;
}
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws IOException {
//Some code
log.info(resultsDirectory);
return RepeatStatus.FINISHED;
}
}
应用程序.yml
file
results: "projectBaseDirectoryPathVariable/src/test/resources/testFiles"
解决方案
你可以稍微破解它。
file
property : projectBaseDirectoryPathVariable
results: ${file.property}/src/test/resources/testFiles
FILE_PROPERTY
现在使用您想要覆盖它的环境变量开始您的测试。这可以在@BeforeAll
via中完成并在withSystem.setEnv(...)
之后清除@AfterAll
System.clearProperty
推荐阅读
- php - Jquery Get 请求不会从 php 文件中回显任何内容
- excel-formula - 无法过滤 sumprod 中的空单元格
- php - 字体文件在控制台上显示为未找到,并且在页面加载时未立即呈现
- python - 实时物体检测python
- c++ - 将两个字符串合并为布尔表达式
- sql - Ms Access 数据库的 SQL 查询。从相似 id 组查询访问数据库
- javascript - 如何通过滚动来缩放元素?
- extendscript - After Effects 脚本 - 来自源素材的 inPoint
- flutter - StorageReference 不是一种类型
- python - 当我不希望它时,Panda 会尝试将我的字符串转换为浮点数