最后,由于使用了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)。
如果用替换
"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(); }}


