Thom
Thom

Reputation: 15042

read flat file from junit test

I am trying to set up a junit test that reads a pdf file to pass into my method, which takes a File parameters. The problem I'm having is that I can't seem to find the pdf file.

I need this to work both inside of eclipse as a single test and once the test has been zipped into a jar file for our automated build.

For simplicity, I've put the postcard.pdf right next to the junit test class. Here's the last thing I've tried.

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");

Help, please?

Upvotes: 0

Views: 2440

Answers (4)

Thom
Thom

Reputation: 15042

I ended up just coding a relative path. Thanks for the help.

Upvotes: 0

Satheesh Cheveri
Satheesh Cheveri

Reputation: 3679

Try with below code, by keeping test.pdf at the root level. And Java Mails Service API supports to add attachment as InputStream/InputStreamSource.

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

Upvotes: 0

Jayan
Jayan

Reputation: 18459

You could include the file (postcard.pdf) in classpath-- by adding to a jar and add that to classpath. Then get the file using getAsResourceStream and write stream to a temporary file.

Upvotes: 0

AlexWien
AlexWien

Reputation: 28727

Normally I only have to change the path such that it works for test data:

File file = new File("./testdata/pdftest/test.pdf");

But if in your case that would not work, then "mock" out the file by defining a IFileProvider interface.

public interface IFileProvider {
  File getFile(URI uri);
}

in junit test use a

class DummyPdfFileProvider implements IFileProvider {
    File getFile(URI uri) {
       // ignore uri
       return new File("./testdata/test.pdf");
    }
}

In Real code use a

class PdfFileProvider implements IFileProvider {
    File getFile(URI uri) {
       // ignore uri
       return new File(uri);
    }
}

Change now real code to use the 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");

Upvotes: 1

Related Questions