无法通过测试用例访问src/main/resources中的文件 [英] Can't access files from src/main/resources via a test-case

查看:185
本文介绍了无法通过测试用例访问src/main/resources中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在src/main/resources中有一个file.dat.

当我尝试测试通过jar文件加载此文件的类时,测试失败,因为它无法在路径(I/O Exception)中找到该文件.我通过测试得到的路径是:

When I try to test a class which loads this file via a jar file, the test fails because its not able to find the file in the path (I/O Exception). The path which I get via test is:

/home/usr/workspace/project/target/test-classes/file.dat

但是target/test-classes中不存在该文件吗?

but the file is not exist in target/test-classes any idea?

推荐答案

在主程序运行期间,src/main/resources中的文件将在类路径上可用,而src/main/resourcessrc/test/resources中的文件将在以下目录中可用测试运行期间的类路径.

Files from src/main/resources will be available on the classpath during runtime of the main program, while files both from src/main/resources and src/test/resources will be available on the classpath during test runs.

检索驻留在类路径上的文件的一种方法是:

One way to retrieve files residing on the classpath is:

Object content = Thread.currentThread().getContextClassLoader().getResource("file.dat").getContent();

..其中content的类型取决于文件内容.您还可以将文件作为InputStream获取:

.. where the type of content depends on the file contents. You can also get the file as an InputStream:

InputStream contentStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("file.dat");

这篇关于无法通过测试用例访问src/main/resources中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆