3

I have a Spring web app that sends generated PDF files via email using MimeMessage and JavaMail and I want to create test cases using JUnit and Mockito to check if the attachments exists.

Is it possible to test this? And if so, whats the best approach?

1 Answers1

2

First, to determine if a message may contain attachments using the following code:

// suppose 'message' is an object of type Message
String contentType = message.getContentType();

if (contentType.contains("multipart")) {
    // this message may contain attachment
}

Then we must iterate through each part in the multipart to identify which part contains the attachment, as follows:

Multipart multiPart = (Multipart) message.getContent();

for (int i = 0; i < multiPart.getCount(); i++) {
    MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
    if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
        // this part is attachment
        // code to save attachment...
    }
}
Seymur Asadov
  • 612
  • 5
  • 19
  • I would like to point out, that there is an emphasis on a word "may" in "this message may contain attachment", because I have a message form 3rd party API with type "text/plain", that still contains attachments. – matvs Jul 09 '21 at 15:27