从 class 路径获取文件,以便测试可以在所有机器上 运行

Get file from class path so tests can run on all machines

我正在使用 Vertx 并尝试测试我从 jsonfile 获取数据的一些参数,目前它可以工作,但我想通过 class 路径获取此文件,以便可以从另一台计算机进行测试。

private ConfigRetriever getConfigRetriever() {
    ConfigStoreOptions fileStore = new ConfigStoreOptions().setType("file").setOptional(true)
            .setConfig(new JsonObject()
                .put("path", "/home/user/MyProjects/MicroserviceBoilerPlate/src/test/resources/local_file.json"));
    ConfigStoreOptions sysPropsStore = new ConfigStoreOptions().setType("sys");
    ConfigRetrieverOptions options = new ConfigRetrieverOptions().addStore(fileStore).addStore(sysPropsStore);
    return ConfigRetriever.create(Vertx.vertx(), options);
}

我上面写的路径是从/home/dir开始的,这使得无法在另一台机器上进行测试。我下面的测试使用此配置

@Test
public void tourTypes() {
    ConfigRetriever retriever = getConfigRetriever();

    retriever.getConfig(ar -> {
        if (ar.failed()) {
            // Failed to retrieve the configuration
        } else {
            JsonObject config = ar.result();

            List<String> extractedIds = YubiParserServiceCustomImplTest.getQueryParameters(config, "tourTypes");
            assertEquals(asList("1", "2", "3", "6"), extractedIds);
        }
    });
}

我想将路径设为 class 路径,以便我可以在所有环境中对其进行测试。 我试图像这样访问 class 路径,但不确定它应该如何访问

private void fileFinder() {
    Path p1 = Paths.get("/test/resources/local_file.json");
    Path fileName = p1.getFileName();
}

将 .json 文件放入项目的 /resources 文件夹 (here an example)。 然后通过 ClassLoader.getResourceAsStream:

访问它
InputStream configFile = ClassLoader.getResourceAsStream("path/to/file.json");
JsonObject config = new JsonParser().parse(configFile);
// Then provide this config to Vertx

如果您已经将文件存储在 "src/test/resources" 中,那么您可以使用

InputStream confFile = getClass().getResourceAsStream("/local_file.json");

URL url = getClass().getResource("/local_file.json");

在你的测试中 class (example)

重要! 在这两种情况下,文件名都可以以 / 开头,也可以不以 / 开头。如果是,它将从 class 路径的根开始。如果不是,它从调用该方法的 class 的包开始。

据我了解,考虑到您的 json 文件的位置,您只需要这样做:

.setConfig(new JsonObject().put("path", "local_file.json"));

参考this