如何将文本文件资源读入 Java 单元测试? [英] How to read a text-file resource into Java unit test?
问题描述
我有一个单元测试需要处理位于 src/test/resources/abc.xml
中的 XML 文件.将文件内容放入 String
的最简单方法是什么?
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
?
推荐答案
最后我找到了一个巧妙的解决方案,感谢 Apache Commons:
Finally I found a neat solution, thanks to 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"
);
}
}
完美运行.文件 src/test/resources/com/example/abc.xml
已加载(我正在使用 Maven).
Works perfectly. File src/test/resources/com/example/abc.xml
is loaded (I'm using Maven).
如果你用 "/foo/test.xml"
替换 "abc.xml"
,这个资源将被加载:src/test/resources/foo/test.xml
If you replace "abc.xml"
with, say, "/foo/test.xml"
, this resource will be loaded: 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();
}
}
这篇关于如何将文本文件资源读入 Java 单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!