简体   繁体   English

如何在JUnit测试中从src / main / resources中读取文件?

[英]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.

相关问题 如何从src / main / java中的src / test / resources中读取道具 - How to read props from src/test/resources in src/main/java 在 JUnit 测试中使用来自 src/main/resources 的实际属性文件和 Spring @PropertySource - Using actual properties file from src/main/resources with Spring @PropertySource in JUnit test 如何使用注释处理器从 src/main/resources 读取文件? - How to read file from src/main/resources with annotation processor? 从 /src/main/resources/ 读取文件 - Read file from /src/main/resources/ Spring xml + JUnit-xml上下文文件在src / test / resources中不起作用,但是在src / main / resources中起作用 - Spring xml + JUnit - xml context file not working in src/test/resources but works in src/main/resources 如何从Java中的src / test / resources中读取Excel文件 - How to read a excel file from src/test/resources in Java Spring JUnit Test 加载 src/test/resources 之外文件的属性 - Spring JUnit Test load properties of file outside of src/test/resources 如何使用FileUtils在JUnit Test中从资源目录读取csv文件 - How to read csv file from resources dir in JUnit Test using FileUtils 从src / main / resources中读取文件作为文件? - Reading file from src/main/resources as File? 如何在Maven中从src / main / resources复制文件? - How do I copy a file from src/main/resources in Maven?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM