How to check MimeMessage for attachments in JUnit or Mockito?

Viewed 1884

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 Answers

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...
    }
}
Related