Java 如何在 JUnit 中获取 src/test/resources 目录的路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28673651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:37:16  来源:igfitidea点击:

How to get the path of src/test/resources directory in JUnit?

javajunit

提问by Rory

I know I can load a file from src/test/resources with:

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

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

But how can I get the full path to the src/test/resources directory, i.e. I don't want to load a file, I just want to know the path of the directory?

但是如何获取src/test/resources目录的完整路径,即我不想加载文件,我只想知道目录的路径?

采纳答案by ashosborne1

Try working with the ClassLoaderclass:

尝试与ClassLoader班级合作:

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

A ClassLoaderis responsible for loading in classes. Every class has a reference to a ClassLoader. This code returns a Filefrom the resource directory. Calling getAbsolutePath()on it returns its absolute Path.

AClassLoader负责加载类。每个类都有一个对 a 的引用ClassLoader。此代码File从资源目录返回一个。调用getAbsolutePath()它会返回它的绝对值Path

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

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

回答by Steve C

You don't need to mess with class loaders. In fact it's a bad habit to get into because class loader resources are notjava.io.File objects when they are in a jar archive.

你不需要搞乱类加载器。事实上,这是一个坏习惯,因为类加载器资源在 jar 存档中时不是java.io.File 对象。

Maven automatically sets the current working directory before running tests, so you can just use:

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

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

resourcesDirectory.getAbsolutePath()will return the correct value if that is what you really need.

resourcesDirectory.getAbsolutePath()如果这是您真正需要的,将返回正确的值。

I recommend creating a src/test/datadirectory if you want your tests to access data via the file system. This makes it clear what you're doing.

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

回答by Antony

I have a Maven3 project using JUnit 4.12 and Java8. In order to get the path of a file called myxml.xmlunder src/test/resources, I do this from within the test case:

我有一个使用 JUnit 4.12 和 Java8 的 Maven3 项目。为了获得一个名为myxml.xmlunder的文件的路径src/test/resources,我在测试用例中执行此操作:

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

Tested on Ubuntu 14.04 with IntelliJ IDE. Reference here.

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

回答by Alexandr

There are differences and constraints in options offered by @Steve C and @ashosborne1. They must be specified, I believe.

@Steve C 和 @ashosborne1 提供的选项存在差异和限制。我相信它们必须被指定。

When can we can use: File resourcesDirectory = new File("src/test/resources");?

我们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), ANDbefore 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 IDEAonly, 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.
  • 1 当测试仅通过 maven 而不是通过 IDE 运行时。
  • 2.1 当测试将通过 maven 或
  • 2.2 通过IDE,只有一个项目导入IDE。(我使用“导入”一词,因为它在 IntelliJ IDEA 中使用。我认为 eclipse 的用户也会导入他们的 maven 项目)。这会起作用,因为当您通过 IDE 运行测试时,工作目录与您的项目相同。
  • 3.1 当测试将通过 maven 或
  • 3.2 通过IDE,多个项目导入IDE(当你不是学生时,通常会导入多个项目),并且在通过IDE运行测试之前,您需要手动配置测试的工作目录。该工作目录应引用包含测试的导入项目。默认情况下,所有导入 IDE 的项目的工作目录只有一个。可能它只是一个限制IntelliJ IDEA,但我认为所有 IDE 都是这样工作的。而这种必须手动完成的配置,一点也不好。使用存在于不同 maven 项目中的几个测试,但导入到一个大的“IDE”项目中,迫使我们记住这一点,不允许放松并从你的工作中获得乐趣。

Solution offered by @ashosborne1 (personally I prefer this one) requires 2 additional requirements that must be done before you run tests. Here is a list of steps to use this solution:

@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):
  • 在“src/test/resources/”中创建一个测试文件夹(“teva”)和文件(“readme”):

    源代码/测试/资源/teva/自述文件

    必须在 test 文件夹中创建文件,否则将无法运行。Maven 忽略空文件夹。

  • 至少一次通过mvn clean install. 它也将运行测试。在不构建整个项目的情况下,通过 Maven 仅运行您的测试类/方法可能就足够了。因此,您的测试资源将被复制到测试类中,这是一个路径:target/test-classes/teva/readme
  • 之后,您可以使用@ashosborne1 已经提供的代码访问该文件夹(对不起,我无法在此项目列表中正确编辑此代码):
public static final String TEVA_FOLDER = "teva"; ... 
URL tevaUrl = YourTest.class.getClassLoader().getResource(TEVA_FOLDER); 
String tevaTestFolder = new File(tevaUrl.toURI()).getAbsolutePath();
public static final String TEVA_FOLDER = "teva"; ... 
URL tevaUrl = YourTest.class.getClassLoader().getResource(TEVA_FOLDER); 
String tevaTestFolder = new File(tevaUrl.toURI()).getAbsolutePath();

Now you can run your test via IDE as many times as you want. Until you run mvn clean. It will drop the target folder.

现在,您可以根据需要通过 IDE 多次运行测试。直到你运行 mvn clean。它将删除目标文件夹。

Creating file inside a test folder and running maven first time, before you run tests via IDE are needed steps. Without these steps, if you just in your IDE create test resources, then write test and run it via IDE only, you'll get an error. Running tests via mvn copies test resources into target/test-classes/teva/readme and they become accessible for a classloader.

在通过 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.

你可能会问,为什么我需要在 IDE 中导入多个 maven 项目,为什么要导入这么多复杂的东西?对我来说,主要动机之一是:让 IDA 相关文件远离代码。我首先在我的 IDE 中创建一个新项目。这是一个伪造的项目,只是一个 IDE 相关文件的持有者。然后,我导入已经存在的 Maven 项目。我强制这些导入的项目只将 IDEA 文件保存在我原来的假项目中。结果我在代码中看不到与IDE相关的文件。SVN 不应该看到它们(请不要提供配置 svn/git 来忽略这些文件)。也非常方便。

回答by Paramesh Korrakuti

If it's a spring project, we can use the below code to get files from src/test/resourcefolder.

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

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

回答by JeanValjean

I would simply use Pathfrom Java 7

我会简单地Path从 Java 7 中使用

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

Neat and clean!

干净整洁!

回答by Noor

The simplest and clean solution I uses, suppose the name of the test class is TestQuery1and there is a resourcesdirectory in your testfolder as follows:

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

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

To get the URI of TestQuery1do:

要获取TestQuery1do的 URI :

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

To get the URI of one of the file TestQuery1, do:

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

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

回答by GreatDantone

Use .getAbsolutePath() on your File object.

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

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

回答by whitebrow

Use the following to inject Hibernate with Spring in your unit tests:

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

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

If you don't have the hibernate.cfg.xmlpresent in your src/test/resourcesfolder it will automatically fall back to the one in your src/main/resourcesfolder.

如果您hibernate.cfg.xmlsrc/test/resources文件夹中没有礼物,它将自动回退到您文件夹中的礼物src/main/resources

回答by Cherry

All content in src/test/resourcesis copied into target/test-classesfolder. So to get file from test resources during maven build you have to load it from test-classesfolder, like that:

中的所有内容src/test/resources都复制到target/test-classes文件夹中。因此,要在 Maven 构建期间从测试资源中获取文件,您必须从test-classes文件夹中加载它,如下所示:

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

Break down:

分解:

  1. getClass().getProtectionDomain().getCodeSource().getLocation().toURI()- give you URI to target/test-classes.
  2. resolve(Paths.get("somefile"))- resolves someFileto target/test-classesfolder.
  1. getClass().getProtectionDomain().getCodeSource().getLocation().toURI()- 给你 URI 到target/test-classes.
  2. resolve(Paths.get("somefile"))- 解析someFiletarget/test-classes文件夹。

Original anwser is taken from this

原始 anwser 取自