首页 > 解决方案 > 为什么我无法在单元测试中列出 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,我想知道为什么会这样以及如何使它们出现在资源数组中。

标签: java

解决方案


你能检查一下你是如何初始化你的Reflections对象的吗?

反思 0.9.11

如果我按照您在问题中描述的方式使用反射(v0.9.11)...

Reflections reflections = new Reflections(new ResourcesScanner());

...然后我可以重新创建这个问题 - 我得到一个 Reflections WARNing。在我的 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

推荐阅读