[英]Spring-boot - Parameterized Test - Access Application.properties in MethodSource
When writing a ParameterizedTest
with spring-boot, one can specify a MethodSource
which provides the values. 使用spring-boot编写ParameterizedTest
时,可以指定提供值的MethodSource
。 The MethodSource
is a static method, which means accessing autowired values and members is not possible. MethodSource
是一个静态方法,这意味着无法访问自动装配的值和成员。
I do define a value in the application.properties
which is crucial for setting up the parameters(it points to the directory containing the data I need). 我在application.properties
定义了一个值,这对于设置参数至关重要(它指向包含我需要的数据的目录)。 How can I access the value within the static method? 如何在静态方法中访问该值?
example code: 示例代码:
application.properties: application.properties:
com.example.directorypath=a/b/c
ApplicationTest: ApplicationTest:
@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);
}
}
A way to resolve the problem of static factory methods is the following: 解决静态工厂方法问题的方法如下:
Annotate the test class with @TestInstance(TestInstance.Lifecycle.PER_CLASS)
which allows factory methods within the test class to not be static. 使用@TestInstance(TestInstance.Lifecycle.PER_CLASS)
注释测试类,它允许测试类中的工厂方法不是静态的。
The annotation is a JUnit5 annotation. 注释是JUnit5注释。
Source: MethodSource 来源: MethodSource
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.