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

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

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


尝试使用ClassLoader类:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("somefile").getFile());
System.out.println(file.getAbsolutePath());

ClassLoader负责装入类。每个类都有一个对ClassLoader的引用。这段代码从资源目录返回一个File。对其调用getAbsolutePath()将返回其绝对路径。

Javadoc for ClassLoader: http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html


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

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

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

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

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


我有一个使用JUnit 4.12和Java8的Maven3项目。 为了获得src/test/resources下名为myxml.xml的文件的路径,我在测试用例中这样做:

@Test
public void testApp()
{
    File inputXmlFile = new File(this.getClass().getResource("/myxml.xml").getFile());
    System.out.println(inputXmlFile.getAbsolutePath());
    ...
}

使用IntelliJ IDE在Ubuntu 14.04上测试。 参考这里。

Note

前置/符号是必要的,因为Class.getResource(String)不一定会显示整个文件路径(缺失)以及FileNotFoundException。


@Steve C和@ashosborne1提供的选项存在差异和限制。我想,它们必须具体说明。

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

1 When tests are going to be run via maven only but not via IDE. 2.1 When tests are going to be run via maven or 2.2 via IDE and only one project is imported into IDE. (I use “imported” term, cause it is used in IntelliJ IDEA. I think users of eclipse also import their maven project). This will work, cause working directory when you run tests via IDE is the same as your project. 3.1 When tests are going to be run via maven or 3.2 via IDE, and more than one projects are imported into IDE (when you are not a student, you usually import several projects), AND before you run tests via IDE, you manually configure working directory for your tests. That working directory should refer to your imported project that contains the tests. By default, working directory of all projects imported into IDE is only one. Probably it is a restriction of IntelliJ IDEA only, but I think all IDEs work like this. And this configuration that must be done manually, is not good at all. Working with several tests existing in different maven projects, but imported into one big “IDE” project, force us to remember this and don’t allow to relax and get pleasure from your work.

@ashosborne1提供的解决方案(我个人更喜欢这个)需要在运行测试之前完成2个额外的要求。下面是使用这个解决方案的步骤列表:

Create a test folder (“teva”) and file (“readme”) inside of “src/test/resources/”: src/test/resources/teva/readme File must be created in the test folder, otherwise, it will not work. Maven ignores empty folders. At least once build project via mvn clean install. It will run tests also. It may be enough to run only your test class/method via maven without building a whole project. As a result your test resources will be copied into test-classes, here is a path: target/test-classes/teva/readme After that, you can access the folder using code, already offered by @ashosborne1 (I'm sorry, that I could not edit this code inside of this list of items correctly):

TEVA_FOLDER = "teva";... URL tevaUrl = YourTest.class.getClassLoader().getResource(TEVA_FOLDER); 字符串tevaTestFolder = new File(tevaul . touri ()).getAbsolutePath();

现在您可以通过IDE运行您的测试,次数不限。直到你把mvn清理干净。它将删除目标文件夹。

在通过IDE运行测试之前,在测试文件夹中创建文件并首次运行maven是必需的步骤。如果没有这些步骤,如果您只是在IDE中创建测试资源,然后编写测试并仅通过IDE运行它,您将会得到一个错误。通过mvn运行测试会将测试资源复制到target/test-classes/teva/readme中,并且类加载器可以访问这些资源。

You may ask, why do I need import more than one maven project in IDE and why so many complicated things? For me, one of the main motivation: keeping IDA-related files far from code. I first create a new project in my IDE. It is a fake project, that is just a holder of IDE-related files. Then, I import already existing maven projects. I force these imported projects to keep IDEA files in my original fake project only. As a result I don't see IDE-related files among the code. SVN should not see them (don't offer to configure svn/git to ignore such files, please). Also it is just very convenient.


如果这是一个spring项目,我们可以使用下面的代码从src/test/resource文件夹中获取文件。

File file = ResourceUtils.getFile(this.getClass().getResource("/some_file.txt"));

我将简单地使用Java 7中的Path

Path resourceDirectory = Paths.get("src","test","resources");

干净利落!


我使用的最简单和干净的解决方案,假设测试类的名称是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");

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

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

使用以下命令在单元测试中注入Hibernate和Spring:

@Bean
public LocalSessionFactoryBean getLocalSessionFactoryBean() {
    LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
    localSessionFactoryBean.setConfigLocation(new ClassPathResource("hibernate.cfg.xml"));
    localSessionFactoryBean.setPackagesToScan("com.example.yourpackage.model");
    return localSessionFactoryBean;
}

如果你的src/test/resources文件夹中没有hibernate.cfg.xml,它会自动回到src/main/resources文件夹中。


src/test/resources中的所有内容都复制到target/test-classes文件夹中。所以在maven构建期间,要从测试资源中获取文件,你必须从test-classes文件夹中加载它,就像这样:

Paths.get(
    getClass().getProtectionDomain().getCodeSource().getLocation().toURI()
).resolve(
    Paths.get("somefile")
).toFile()

分解:

getClass(). getprotectiondomain (). getcodesource (). getlocation (). touri() -给你目标/测试类的URI。 resolve(Paths.get("somefile")) -将somefile解析到target/test-classes文件夹。

原来的答案是这样的


在一般情况下,不能将资源文件夹中的文件用于测试。原因是资源文件夹中的资源文件存储在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;
}

List<String> lines = Files.readAllLines(Paths.get("src/test/resources/foo.txt"));
lines.forEach(System.out::println);

在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";

你可以去你想去的地方

new File(".").getAbsolutePath()

然后,您可以派生src/test/resources的路径 通常只是

new File("src/test/resources")

哇,正确答案还不在这里!

MyClass.class.getResource("/somefile");
MyClass.class.getResourceAsStream("/somefile");

https://javachannel.org/posts/how-to-access-static-resources/