如何将文本文件资源读取到Java单元测试中?

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

回答:

最后,由于使用了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();

}

}

以上是 如何将文本文件资源读取到Java单元测试中? 的全部内容, 来源链接: utcz.com/qa/428731.html

回到顶部