How to Mock PDDocument.load in Junit5
Hi Team,
I have a code like this in my service class.
try (ResourceResolver resourceResolver = request.getResourceResolver();PDDocument finalDoc = new PDDocument()){
requestStringJson = new JSONObject(IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8));
PDDocument pdfTemplate = null;
if(resourceResolver.getResource(/content/dam/XXXXXX/xxx/TEST_PDF.pdf) != null) {
Resource resource = resourceResolver.getResource(/content/dam/XXXXXX/xxx/TEST_PDF.pdf);
Asset pdfFile = resource.adaptTo(Asset.class);
pdfTemplate = PDDocument.load(pdfFile.getImagePreviewRendition().getStream());
//update fields
PDDocumentCatalog docCatalog = pdfTemplate.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();
PDTextField field;
field = (PDTextField) acroForm.getField(PDFConstants.NAME);
..................................................................
I am facing issue while writting junit for this class.
@Test
void downloadPDFTest() throws ServiceException, IOException, JSONException {
String path = "/content/dam/XXXXXX/xxx/TEST_PDF.pdf";
try (MockedStatic<IOUtils> ioUtilsMockedStatic = Mockito.mockStatic(IOUtils.class)) {
ioUtilsMockedStatic.when(() -> IOUtils.toString((InputStream) any(), (Charset) any())).thenReturn("{\"name\":\"John Doe\"}");
when(request.getResourceResolver()).thenReturn(resourceResolver);
when(resourceResolver.getResource(path)).thenReturn(resource);
when(resource.adaptTo(Asset.class)).thenReturn(asset);
when(asset.getImagePreviewRendition()).thenReturn(rendition);
when(rendition.getStream()).thenReturn(inputStream);
when(PDDocument.load(inputStream)).thenReturn(document);
It is failing at this line throwing null pointer exception - when(PDDocument.load(inputStream)).thenReturn(document); . Can anyone share me the pointers or suggestions on is there a way to mock this in Junit.
