【问题标题】:Springboot Integration test: Update application.yml property with pwd before bean initializationSpring Boot 集成测试:在 bean 初始化之前使用 pwd 更新 application.yml 属性
【发布时间】:2021-04-02 23:10:18
【问题描述】:

我正在编写 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;
    }
}

application.yml

file
 results: "projectBaseDirectoryPathVariable/src/test/resources/testFiles"

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    你可以稍微破解一下。

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

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

    【讨论】:

    • 集成测试中如何从 application.yml 访问 file.property 的值?
    • 我无法在集成测试中访问 file.property。有人可以帮忙吗?
    猜你喜欢
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 2020-03-02
    • 2019-03-07
    • 2012-12-20
    • 2021-03-29
    • 2020-11-22
    • 1970-01-01
    相关资源
    最近更新 更多