我知道我可以从src/test/resources加载一个文件:

getClass().getResource("somefile").getFile()

但是我怎么能得到src/test/resources目录的完整路径,即我不想加载一个文件,我只想知道目录的路径?


当前回答

你不需要干扰类加载器。事实上,这是一个不好的习惯,因为当类装入器资源在jar存档中时,它们不是java.io.File对象。

Maven在运行测试之前自动设置当前工作目录,因此您可以使用:

    File resourcesDirectory = new File("src/test/resources");

getabsolutepath()将返回正确的值,如果这是你真正需要的。

如果您希望您的测试通过文件系统访问数据,我建议创建一个src/test/data目录。这让你清楚地知道你在做什么。

其他回答

我使用的最简单和干净的解决方案,假设测试类的名称是TestQuery1,并且在您的测试文件夹中有一个资源目录,如下所示:

├── java
│   └── TestQuery1.java
└── resources
    └── TestQuery1
        ├── query.json
        └── query.rq

要获得TestQuery1的URI,请执行以下操作:

URL currentTestResourceFolder = getClass().getResource("/"+getClass().getSimpleName());

要获取文件TestQuery1的URI,请执行以下操作:

File exampleDir = new File(currentTestResourceFolder.toURI());
URI queryJSONFileURI = exampleDir.toURI().resolve("query.json");

在一般情况下,不能将资源文件夹中的文件用于测试。原因是资源文件夹中的资源文件存储在jar中。它们在文件系统中没有真正的路径。

最简单的解决方法是:

将文件从资源复制到临时文件夹,并获取该临时文件的路径。 使用临时路径执行测试。 删除临时文件。

来自JUnit的TemporaryFolder可以用来创建临时文件,并在测试完成后删除它。番石榴库中的类用于从资源文件夹中复制文件。

请注意,如果我们使用resources文件夹中的子文件夹,就像good文件夹一样,我们不必在资源路径中添加前导/。

public class SomeTest {

    @Rule
    public TemporaryFolder tmpFolder = new TemporaryFolder();


    @Test
    public void doSomethinge() throws IOException {
        File file = createTmpFileFromResource(tmpFolder, "file.txt");
        File goodFile = createTmpFileFromResource(tmpFolder, "good/file.txt");

        // do testing here
    }

    private static File createTmpFileFromResource(TemporaryFolder folder,
                                                  String classLoaderResource) throws IOException {
        URL resource = Resources.getResource(classLoaderResource);

        File tmpFile = folder.newFile();
        Resources.asByteSource(resource).copyTo(Files.asByteSink(tmpFile));
        return tmpFile;
    }

}

使用Spring,你可以很容易地从资源文件夹(main/resources或test/resources)中读取:

例如,创建一个文件test/resources/subfolder/sample.json

@Test
public void testReadFile() {
    String json = this.readFile("classpath:subfolder/sample.json");
    System.out.println(json);
}

public String readFile(String path) {
    try {
        File file = ResourceUtils.getFile(path);
        return new String(Files.readAllBytes(file.toPath()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

在Spring中,你可以这样使用:

import org.springframework.core.io.ClassPathResource;

// Don't worry when use a not existed directory or a empty directory
// It can be used in @before
String dir = new ClassPathResource(".").getFile().getAbsolutePath()+"/"+"Your Path";

在File对象上使用. getabsolutepath()。

getClass().getResource("somefile").getFile().getAbsolutePath()