java - 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);
}
}
解决方案
解决静态工厂方法问题的一种方法如下:
注释测试类@TestInstance(TestInstance.Lifecycle.PER_CLASS)
,允许测试类中的工厂方法不是静态的。
注释是一个 JUnit5 注释。
来源:方法来源
推荐阅读
- pelican - 如何在 index.html 中包含降价文件?
- powershell - 替代测试路径,使用凭证,到不同域上的主机,在文件夹路径中使用通配符
- android - 为什么我的 ElegantNumberButton 没有显示 +(加号) 符号?
- php - 为什么我不能断言工作已经被派遣?
- c# - 如何按标签查找视图?
- azure - Azure k8s 仪表板未打开
- python - MCP9600 带覆盆子
- javascript - 如何使用 lodash 对对象进行分组?
- reactjs - 从 Ref 获取 React-Native 元素的高度
- algorithm - 每次查询后的最大矩形大小(算法)