如何将文本文件资源读入 Java 单元测试?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3891375/
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-14 06:26:00  来源:igfitidea点击:

How to read a text-file resource into Java unit test?

javaunit-testing

提问by yegor256

I have a unit test that needs to work with XML file located in src/test/resources/abc.xml. What is the easiest way just to get the content of the file into String?

我有一个单元测试需要使用位于src/test/resources/abc.xml. 将文件内容放入的最简单方法是String什么?

采纳答案by yegor256

Finally I found a neat solution, thanks to Apache Commons:

最后我找到了一个巧妙的解决方案,感谢Apache Commons

package com.example;
import org.apache.commons.io.IOUtils;
public class FooTest {
  @Test 
  public void shouldWork() throws Exception {
    String xml = IOUtils.toString(
      this.getClass().getResourceAsStream("abc.xml"),
      "UTF-8"
    );
  }
}

Works perfectly. File src/test/resources/com/example/abc.xmlis loaded (I'm using Maven).

完美运行。文件src/test/resources/com/example/abc.xml已加载(我正在使用 Maven)。

If you replace "abc.xml"with, say, "/foo/test.xml", this resource will be loaded: src/test/resources/foo/test.xml

如果您替换"abc.xml"为,例如"/foo/test.xml",此资源将被加载:src/test/resources/foo/test.xml

You can also use Cactoos:

您还可以使用Cactoos

package com.example;
import org.cactoos.io.ResourceOf;
import org.cactoos.io.TextOf;
public class FooTest {
  @Test 
  public void shouldWork() throws Exception {
    String xml = new TextOf(
      new ResourceOf("/com/example/abc.xml") // absolute path always!
    ).asString();
  }
}

回答by Kirk Woll

First make sure that abc.xmlis being copied to your output directory. Then you should use getResourceAsStream():

首先确保abc.xml正在将其复制到您的输出目录。那么你应该使用getResourceAsStream()

InputStream inputStream = 
    Thread.currentThread().getContextClassLoader().getResourceAsStream("test/resources/abc.xml");

Once you have the InputStream, you just need to convert it into a string. This resource spells it out: http://www.kodejava.org/examples/266.html. However, I'll excerpt the relevent code:

拥有 InputStream 后,您只需要将其转换为字符串。该资源详细说明:http: //www.kodejava.org/examples/266.html。但是,我将摘录相关代码:

public String convertStreamToString(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(
                    new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {        
        return "";
    }
}

回答by Glen Best

Assume UTF8 encoding in file - if not, just leave out the "UTF8" argument & will use the default charset for the underlying operating system in each case.

假设文件中的 UTF8 编码 - 如果不是,只需省略“UTF8”参数并在每种情况下使用底层操作系统的默认字符集。

Quick way in JSE 6 - Simple & no 3rd party library!

JSE 6 中的快速方法 - 简单且没有 3rd 方库!

import java.io.File;
public class FooTest {
  @Test public void readXMLToString() throws Exception {
        java.net.URL url = MyClass.class.getResource("test/resources/abc.xml");
        //Z means: "The end of the input but for the final terminator, if any"
        String xml = new java.util.Scanner(new File(url.toURI()),"UTF8").useDelimiter("\Z").next();
  }
}

Quick way in JSE 7

JSE 7 中的快捷方式

public class FooTest {
  @Test public void readXMLToString() throws Exception {
        java.net.URL url = MyClass.class.getResource("test/resources/abc.xml");
        java.nio.file.Path resPath = java.nio.file.Paths.get(url.toURI());
        String xml = new String(java.nio.file.Files.readAllBytes(resPath), "UTF8"); 
  }

Quick way since Java 9

自 Java 9 以来的快速方法

new String(getClass().getClassLoader().getResourceAsStream(resourceName).readAllBytes());

Neither intended for enormous files though.

不过,两者都不打算用于巨大的文件。

回答by Guido Celada

You can try doing:

你可以尝试这样做:

String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");

回答by pablo.vix

Right to the point :

切入正题:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());

回答by Datageek

With the use of Google Guava:

使用谷歌番石榴:

import com.google.common.base.Charsets;
import com.google.common.io.Resources;

public String readResource(final String fileName, Charset charset) throws Exception {
        try {
            return Resources.toString(Resources.getResource(fileName), charset);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
}

Example:

例子:

String fixture = this.readResource("filename.txt", Charsets.UTF_8)

回答by ikryvorotenko

Here's what i used to get the text files with text. I used commons' IOUtils and guava's Resources.

这是我用来获取带有文本的文本文件的方法。我使用了 commons 的 IOUtils 和 guava 的 Resources。

public static String getString(String path) throws IOException {
    try (InputStream stream = Resources.getResource(path).openStream()) {
        return IOUtils.toString(stream);
    }
}

回答by IgorGanapolsky

You can use a Junit Rule to create this temporary folder for your test:

您可以使用 Junit 规则为您的测试创建此临时文件夹:

@Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); File file = temporaryFolder.newFile(".src/test/resources/abc.xml");

@Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); File file = temporaryFolder.newFile(".src/test/resources/abc.xml");