junit 如何在测试期间使用非静态@TempDir和自定义@ TempationProperties

628mspwn  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(177)

我正在开发一个Spring Batch应用程序,它处理图像文件,其中图像的路径可以使用application.yml配置:

files:
    image-path: /var/images

字符串
我尝试在我的一个Sping Boot 集成测试中使用一个用@TempDir注解的non-static字段,以便为每个测试获得一个新的临时文件夹:

@SpringBatchTest
@SpringBootTest
@SpringJUnitConfig(classes = ImageBatchJobApplication.class)
class ImageBatchJobTests {

    @TempDir
    private Path imagePath;

    ...
}


问题是我需要将这个临时文件夹路径传递给我的自定义@ConfigurationProperties类:

@ConfigurationProperties(prefix = "files")
public record MyConfiguration(String imagePath) { }


我尝试使用@DynamicPropertySource,将临时目录添加到注册表中:

@DynamicPropertySource
private static void testProperties(DynamicPropertyRegistry registry) {
    registry.add("files.image-path", imagePath::toString);
}


当然,在静态方法中,我不能访问非静态的imagePath字段。我曾想过使用自定义的ApplicationCOntextInitializer,但在那里我会遇到如何访问示例变量的同样问题。有人知道如何在每次测试之前将@TempDir路径传递给MyConfiguration吗?

bksxznpy

bksxznpy1#

一种选择是在beforeEach方法中注入用@ConfigurationProperties注解的配置类,并更新那里的值:

@DirtiesContext
@SpringBatchTest
@SpringBootTest
@SpringJUnitConfig(classes = ImageBatchJobApplication.class)
class ImageBatchJobApplicationTests {

    @TempDir
    private Path imagePath;

    @BeforeEach
    public void setup(@Autowired MyConfiguration config) {
        config.setImagePath(imagePath.toString());
    }
}

字符串

相关问题