gpt4 book ai didi

java - 在单元测试中访问资源

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:11:54 26 4
gpt4 key购买 nike

我使用的是 JUnit 4、Java 8 和 Gradle 1.12。我有一个需要加载的默认 json 文件。我的项目有src/main/java/(包含项目源),src/main/resources/(空),src/test/java/(单元测试源)和 src/test/resources/(要加载的 json 数据文件)目录。 build.gradle 文件位于根目录中。

在我的代码中我有:

public class UnitTests extends JerseyTest
{
@Test
public void test1() throws IOException
{
String json = UnitTests.readResource("/testData.json");
// Do stuff ...
}

// ...
private static String readResource(String resource) throws IOException
{
// I had these three lines combined, but separated them to find the null.
ClassLoader c = UnitTests.class.getClassLoader();
URL r = c.getSystemResource(resource); // This is returning null. ????
//URL r = c.getResource(resource); // This had the same issue.
String fileName = r.getFile();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName)))
{
StringBuffer fileData = new StringBuffer();
char[] buf = new char[1024];
int readCount = 0;
while ((readCount = reader.read(buf)) != -1)
{
String readData = String.valueOf(buf, 0, readCount);
fileData.append(readData);
}

return fileData.toString();
}
}
}

根据我的阅读,这应该可以让我访问资源文件。但是,当我尝试使用 URL 时出现空指针异常,因为 getSystemResource() 调用返回 null。

如何访问我的资源文件?

最佳答案

资源名称不以斜杠开头,因此您需要去掉它。最好使用 UnitTests.getClassLoader().getResourceAsStream("the/resource/name") 读取资源,或者,如果需要 Filenew File(UnitTests.getClassLoader().getResource("the/resource/name").toURI()).

在 Java 8 上,您可以尝试类似的操作:

URI uri = UnitTests.class.getClassLoader().getResource("the/resource/name").toURI();
String string = new String(Files.readAllBytes(Paths.get(uri)), Charset.forName("utf-8"));

关于java - 在单元测试中访问资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24499692/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com