首页 > 解决方案 > 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"

标签: javaspringspring-boot

解决方案


你可以稍微破解它。

file
   property : projectBaseDirectoryPathVariable 
   results: ${file.property}/src/test/resources/testFiles

FILE_PROPERTY现在使用您想要覆盖它的环境变量开始您的测试。这可以在@BeforeAllvia中完成并在withSystem.setEnv(...)之后清除@AfterAllSystem.clearProperty


推荐阅读