首页 > 解决方案 > Spring-boot - 参数化测试 - 访问 MethodSource 中的 Application.properties

问题描述

使用 spring-boot编写 aParameterizedTest时,可以指定MethodSource提供值的 a。这MethodSource是一个静态方法,这意味着无法访问自动装配的值和成员。

我确实在其中定义了一个值,application.properties这对于设置参数至关重要(它指向包含我需要的数据的目录)。如何访问静态方法中的值?

示例代码:

应用程序属性:

com.example.directorypath=a/b/c

应用测试:

@ActiveProfiles("dev")
@RunWith(SpringRunner.class)
@SpringBootTest
public class RdxApplicationTests {

    @Value("${com.example.directorypath}")
    private String directory;

    @ParameterizedTest
    @MethodSource("provideDirectories")
    public void test(File dir){
        System.out.println(dir);
    }

    private static Stream<Arguments> provideDirectories(){
        //here is the place I need the value
        File f = new File(directory);

        return Arrays.stream(Objects.requireNonNull(f.listFiles())).map(Arguments::of);

    }
}

标签: javaspring-bootjunit

解决方案


解决静态工厂方法问题的一种方法如下:

注释测试类@TestInstance(TestInstance.Lifecycle.PER_CLASS),允许测试类中的工厂方法不是静态的。

注释是一个 JUnit5 注释。

来源:方法来源


推荐阅读