java - 为什么我无法在单元测试中列出 Java 资源?
问题描述
我有一些文件src/main/resources
希望复制到文件系统中。我想获取这些资源的列表,然后遍历它们并将它们复制出来。我正在使用 Reflections 的 v0.9.11来解析资源目录。
public List<String> getMyResources() {
Reflections reflections = new Reflections(new ResourcesScanner());
Set<String> resources = reflections.getResources(Pattern.compile(".*"));
return new ArrayList<>(resources);
}
我想测试我是否可以在单元测试中找到这些文件:
@Test
public void getMyResources_returnsCorrectFiles() throws IOException {
MyResourceFinder finder = new MyResourceFinder();
List<String> resources = finder.getMyResources();
assertEquals(3, resources.size());
// other tests to check the files are found
}
但是,没有找到资源,即resources
数组的长度为 0。当我将测试资源放入src/test/resources
. 但是,我可以按名称查找和读取单个资源,如下所示:
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/path/to/my/resource.yaml")));
我做错了什么以及如何列出资源?
编辑:要清楚,我可以看到构建的 jar 中列出的资源。但是,我的单元测试无法列出其中的资源src/main/resources
,我想知道为什么会这样以及如何使它们出现在资源数组中。
解决方案
你能检查一下你是如何初始化你的Reflections
对象的吗?
反思 0.9.11
如果我按照您在问题中描述的方式使用反射(v0.9.11)...
Reflections reflections = new Reflections(new ResourcesScanner());
...然后我可以重新创建这个问题 - 我得到一个 Reflections WARN
ing。在我的 jUnit 测试中,我预计会找到 17 个资源,但没有找到:
2020-03-11 14:54:59.039 [WARN ] [main] Reflections - given scan urls are empty. set urls in the configuration
...
java.lang.AssertionError: expected:<17> but was:<0>
但是,如果我将代码更改为此...
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setUrls(ClasspathHelper.forPackage("your.package.name.here"))
.setScanners(new ResourcesScanner()));
...然后我明白了:
2020-03-11 14:52:54.107 [INFO ] [main] Reflections - Reflections took 10 ms to scan 2 urls, producing 17 keys and 17 values
我的单元测试通过了。
反思 0.9.12
出于兴趣,如果您升级到 0.9.12,您的方法会引发相同的警告,但也会引发运行时异常:
org.reflections.ReflectionsException: Scanner ResourcesScanner was not configured
推荐阅读
- python - 在应用引擎中为不同的服务创建 cron 作业
- scala - 如何将 df 单元格中的数组转换为单个列名?
- node.js - 如何使用 history.push(/nextpath) 或 windows.location?
- python - 相同列名的数据透视表 - 必须在数据透视后重复
- html - 使用角度在移动应用程序中推送通知
- reactjs - 错误:未找到来自 react-redux 的上下文。如果您使用 react-redux v6,则需要 v3.*.* 版本的 react-redux-firebase
- c++ - 所有的 C++ 头文件都是一个类吗?
- wordpress - Wordpress WooCommerce:垃圾/删除产品操作
- python - 如何在 django 中保存一个 html 文件?
- libgit2 - 如何通过在 libgit2 中创建内存索引来提交文件?