Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从junit测试中读取平面文件_Java_File_Junit - Fatal编程技术网

Java 从junit测试中读取平面文件

Java 从junit测试中读取平面文件,java,file,junit,Java,File,Junit,我正在尝试设置一个junit测试,该测试读取一个pdf文件,并将其传递到我的方法中,该方法接受一个文件参数。我遇到的问题是,我似乎找不到pdf文件 我需要它作为一个单独的测试在eclipse内部工作,并且一旦测试被压缩到一个jar文件中用于我们的自动构建 为了简单起见,我将postcard.pdf放在junit测试类的旁边。这是我试过的最后一件事 URL url = getClass().getClassLoader().getResource("postcard.pdf"); URI uri

我正在尝试设置一个junit测试,该测试读取一个pdf文件,并将其传递到我的方法中,该方法接受一个文件参数。我遇到的问题是,我似乎找不到pdf文件

我需要它作为一个单独的测试在eclipse内部工作,并且一旦测试被压缩到一个jar文件中用于我们的自动构建

为了简单起见,我将postcard.pdf放在junit测试类的旁边。这是我试过的最后一件事

URL url = getClass().getClassLoader().getResource("postcard.pdf");
URI uri = url.toURI();
File file = new File(uri);
javamailService.sendMessage(MAILUSER, REPLY_TO, SUBJECT, file, MimeType.pdf);
fail("Not yet implemented");

请提供帮助?

通常,我只需更改路径,使其适用于测试数据:

File file = new File("./testdata/pdftest/test.pdf");
但是,如果在您的情况下这不起作用,那么通过定义
IFileProvider
接口来“模拟”该文件

public interface IFileProvider {
  File getFile(URI uri);
}
在junit测试中,使用

class DummyPdfFileProvider implements IFileProvider {
    File getFile(URI uri) {
       // ignore uri
       return new File("./testdata/test.pdf");
    }
}
在实际代码中使用

class PdfFileProvider implements IFileProvider {
    File getFile(URI uri) {
       // ignore uri
       return new File(uri);
    }
}
现在更改真实代码以使用
PdfFileProvider

IFileProvider fileProvider = new PdfFileProvider();

URL url = getClass().getClassLoader().getResource("postcard.pdf");
URI uri = url.toURI();
File file = fileProvider.getFile(uri);
javamailService.sendMessage(MAILUSER, REPLY_TO, SUBJECT, file, MimeType.pdf);
// and remove the fail below:
//fail("Not yet implemented");

通过将test.pdf保持在根级别,尝试使用以下代码。Java邮件服务API支持将附件添加为InputStream/InputStreamSource

InputStream configStream = getClass().getResourceAsStream("test.pdf");

您可以在类路径中包含该文件(明信片.pdf)——通过添加到jar并将其添加到类路径中。然后使用和写入获取文件

我最后只是编写了一个相对路径。谢谢您的帮助。

您解决了错误的问题,尽管我很感激您提供的信息。我需要做的就是创建一个文件。如果不对绝对路径进行硬编码,我似乎无法获取文件,而绝对路径将在我们的测试服务器和其他工作站上中断。