I have 1 java class which is rendering URL as PDF , below is the sample code:
public byte[] renderURLAsPDF(final String url, final Long id) throws SomeException {
try {
URLConnection connection = new URL(url).openConnection();
connection.setRequestProperty(HttpHeaders.USER_AGENT, "");
try (InputStream openStream = connection.getInputStream()) {
PDFVerifierInputStream pdfInputStream = new PDFVerifierInputStream(openStream);
return IOUtils.toByteArray(pdfInputStream);
}
} catch (FileNotFoundException ex) {
throw SomeException.newInstanceWithHttpNotFound("Failed to find a PDF file for Booking Ref : " + itineraryItemId );
} catch (IOException e) {
throw new OrionException("Failed to render URL As PDF for Booking Ref: " + itineraryItemId, e);
}
}
So I want to create 1 test for this class which will throw FileNotFoundException
.
What I have done to test this method I created mocked connection but it am not able to throw that FileNotFoundException
from inputStream.getInputStream()
code which i created.
public void renderURLAsPDFFileNotFoundException() throws Exception {
URLConnection urlConnection = mock(URLConnection.class);
URLStreamHandler stubUrlHandler = new URLStreamHandler() {
@Override
protected URLConnection openConnection(URL u) throws IOException {
return urlConnection;
}
};
String url = "https://myurl.com";
IOException fileNotFoundException = new FileNotFoundException(url);
given(urlConnection.getInputStream()).willThrow(fileNotFoundException);
SomeException exception = assertThrows(SomeException.class, () -> ticketPDFGateway.renderURLAsPDF(url, ITEM_ID));
assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
}
Actaully I am new to mockito, I mocked the connection but it is still throwing IOException
, so Can anyone help me on this how can I properly mock the connection so Java class will know the mocked connection for the test class.