Reputation: 3973
This code runs well in my locally but gives file not found exception when we build using bamboo. Any idea/workaround?
final static String FILE_NAME ="/src/test/java/com/statement/SamplePDFStatementFile.txt";
file = new File(FILE_NAME);
FileInputStream fis = new FileInputStream(file);
I basically want to test a class which reads a file. Here is the Complete Code.
//Main Class
public class PdfRenderer {
public void render(PdfFile pdfFile) throws IOException {
FileInputStream fis = new FileInputStream(pdfFile.getFile());
final HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
response.setHeader("Content-Disposition", " attachment; filename=" + pdfFile.getAttachmentName());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = fis.read(buff, 0, buff.length))) {
response.getOutputStream().write(buff, 0, bytesRead);
}
response.getOutputStream().flush();
}
}
//Test
public class PdfRendererTest{
PdfFile pdfFile;
File file;
@Test
public void test_DetailStatementsByAccountNumber() throws Exception {
new AbstractSeamTest.ComponentTest() {
PdfRenderer actionBean = new PdfRenderer();
URL url = this.getClass().getResource("/SamplePDFStatementFile.txt");
final String FILE_NAME = url.getFile();
protected void testComponents() throws Exception {
file = new File(FILE_NAME);
context.checking(new Expectations() {{
one(pdfFile).getFile();
will(returnValue(file));
one(pdfFile).getAttachmentName();
will(returnValue(file.getName()));
}});
actionBean.render(pdfFile);
}
}.run();
}
}
I want to set an expectation that pdfFile.getFile() returns SamplePDFStatementFile.txt. If I use getResourceAsStream, am not sure how to convert it to a File Object.
OK.. so now I am using. Looks like thats the answer :)
public void inputStreamToFile() throws Exception{
InputStream inputStream = this.getClass().getResourceAsStream("/SamplePDFStatementFile.txt");
file = File.createTempFile("abc","def");
OutputStream out = new FileOutputStream(file);
int length = 0;
byte[] bytes = new byte[1024];
while ((length = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, length);
}
inputStream.close();
out.flush();
out.close();
}
Upvotes: 1
Views: 18876
Reputation: 242786
There are no reliable ways to reference files relative to the project root folder.
You need to reference this file as a resource instead. As far as I see, you use Maven. If so, you need to put this file into /src/test/resources
rather than /src/test/java
(perhaps you can also configure Maven to get resources from /src/test/java
, but it would be a violation of Maven directory layout convention).
After that you can load this file as
InputStream fis = getClass()
.getResourceAsStream("/com/statement/SamplePDFStatementFile.txt");
Or, if the current class is in the com.statement
package, as
InputStream fis = getClass().getResourceAsStream("SamplePDFStatementFile.txt");
Upvotes: 6