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

yeg*_*256 196 java unit-testing

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

yeg*_*256 212

最后,我发现了一个简洁的解决方案,感谢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"
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

你也可以使用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();
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 可以在没有外部库依赖的情况下完成此操作. (8认同)
  • @ yegor256因为它是一个单元测试关闭资源是*特别重要."单元"测试应该快速且自包含,使资源保持开放,可能在测试运行期间,意味着测试运行速度最慢,最坏的情况是难以诊断. (5认同)
  • 嘿@ yegor256,是不是`IOUtils.toString`静态方法?根据你众所周知的"静态"不喜欢,你现在怎么解决呢? (5认同)
  • 同样紧凑,但是适当地关闭了输入流:`IOUtils.toString(this.getClass()。getResource(“ foo.xml”),“ UTF-8”)`。 (3认同)
  • 仅当文件位于同一个包中时才有效.如果他们不在同一个包中怎么办? (2认同)
  • 这对我有用 `IOUtils.toString( this.getClass().getClassLoader().getResourceAsStream("abc.xml"), "UTF-8" );` (2认同)
  • 从 Apache Commons 2.6 开始,您可以使用 `resourceToString` 来代替更清晰的代码:`String xml = IOUtils.resourceToString("/com/example/abc.xml", StandardCharsets.UTF_8));`。请注意,在这种情况下,文件路径必须是绝对路径。 (2认同)

pab*_*vix 109

正确的观点:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());
Run Code Online (Sandbox Code Playgroud)

  • 在使用 junit 测试并希望通过将 xls 文件加载到 byte[] 形式来设置测试时对我有用。 (2认同)
  • OP询问“仅将文件内容转换为String的最简单方法是什么?” 如果直接回答这个问题,那就更好了。 (2认同)
  • getClass().getClassLoader().getResource("test.xml"); (2认同)
  • File file = new File(getClass().getResource("/responses/example.json").getFile()); 在没有 getClassLoader() 的情况下,似乎也能正常工作。 (2认同)

Gle*_*est 53

假设UTF8编码在文件中 - 如果没有,只省略"UTF8"参数,并将在每种情况下使用底层操作系统的默认字符集.

JSE 6中的快捷方式 - 简单且无第三方库!

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

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"); 
  }
Run Code Online (Sandbox Code Playgroud)

虽然没有打算用于大量文件.

  • 以上将文件内容直接读入内存中的字符串.因此,例如,如果你有4GB的内存,那么1-4GB之间的文件可能归类为"巨大",因为它将消耗非常大比例的内存资源(除了页面交换到磁盘).对于大文件,最好是流 - 读取块,而不是一次读取. (2认同)
  • java7版本完美,提示:使用StandardCharsets.UTF_8以避免unsupportedEncodingException (2认同)

Kir*_*oll 13

首先确保将abc.xml其复制到输出目录.然后你应该使用getResourceAsStream():

InputStream inputStream = 
    Thread.currentThread().getContextClassLoader().getResourceAsStream("test/resources/abc.xml");
Run Code Online (Sandbox Code Playgroud)

拥有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 "";
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 什么是“你的输出目录”? (3认同)
  • 如何将 `abc.xml` 复制到输出目录?@柯沃尔 (2认同)

Dat*_*eek 8

使用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);
        }
}
Run Code Online (Sandbox Code Playgroud)

例:

String fixture = this.readResource("filename.txt", Charsets.UTF_8)
Run Code Online (Sandbox Code Playgroud)


Gui*_*ada 5

你可以试试:

String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");
Run Code Online (Sandbox Code Playgroud)

  • 你为什么剥离新线? (3认同)
  • @zudduz对不起,我不记得了,这是2年前的事 (2认同)
  • IOUtils.toString toString(stream) 也已弃用。需要在 IOUtils.toString toString(stream, Charsets.UTF_8) 中传递字符集(import com.google.common.base.Charsets;) (2认同)

归档时间:

查看次数:

234535 次

最近记录:

7 年,11 月 前