[英]How to read file from src/main/resources relative in a JUnit test?
I have a junit testcase and a file that I want to load during that test. 我有一个junit测试用例和一个我想在该测试期间加载的文件。 The file is placed under
src/main/resources
, whereas the packages are named same as the java testfile: 该文件位于
src/main/resources
,而这些包的名称与java testfile相同:
src/test/java/my/path/to/FileTest.java
src/test/resource/my/path/to/test.txt
Usage: 用法:
public class FileTest {
@Test
public void testRead() {
String content = IOUtils.toString(this.getClass().getResourceAsStream("test.txt"), Charset.defaultCharset());
System.out.println(content);
}
}
Exception when running the testcase in IDE: 在IDE中运行测试用例时出现异常:
java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:113)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:2272)
at org.apache.commons.io.IOUtils.toString(IOUtils.java:1041)
What might be wrong here? 这可能有什么问题?
我结束了将testfiles直接放入/src/main/resources
而没有子包,并使用。
PropertiesLoaderUtils.loadProperties(new ClassPathResource(filename));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.