function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sandeep TechAffinitySandeep TechAffinity 

Need help to write test class on Inbound Email services Test Class with Attachments.

Hello Guys,

I have a Test class on InboundEmail Service Class and it includes sObjects Like Lead, EmailMessage, Task, User, and Attachments Can anyone please help me with the Test class.
global class captureEmailResponses implements Messaging.InboundEmailHandler {
    //  Handles inbound email replies from leads and puts the details into Email Messages which creates a
    //  Activity Entry. This will also update the lead status to patient replied.
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){
        // Create an InboundEmailResult object for returning the result of the
        // Apex Email Service
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        // Set the activity name to the email from name
        String Activityname = email.fromname;
        // Find the lead by the from address
        String fromemailaddresss = email.fromAddress;
        String des = email.plainTextBody;
        String tasksubject = email.subject;
        try {
            // Lets get the original message
            EmailMessage originalMessage = [SELECT ReplyToEmailMessageId, MessageIdentifier, ThreadIdentifier, CreatedById, ActivityId FROM EmailMessage WHERE MessageIdentifier = :email.inReplyTo LIMIT 1];
            
            // Get Task from original Message
            Task linkedTask = [SELECT Id, WhoId FROM Task WHERE Id = :originalMessage.ActivityId LIMIT 1];
            // Get lead from WhoId
            Lead lead = [SELECT Id, Name, Email, ShareGroupId__c, LastModifiedById, Status FROM Lead 
                         WHERE Id = :linkedTask.WhoId LIMIT 1];
            User lastUser = [SELECT Id, Email FROM User
                             WHERE Id = :originalMessage.CreatedById LIMIT 1];
            // Create a email message because we use enhanced emails and it creates the activity automatically.
            EmailMessage[] newEmail = new EmailMessage[0];
            String[] toUsers = new String[]{lead.LastModifiedById};
                newEmail.add(new EmailMessage(FromAddress = email.fromAddress,
                                              FromName = email.fromName,
                                              Incoming = True,
                                              ToAddress = lastUser.Email,
                                              //ToAddress = email.toAddresses[0],
                                              Subject = email.subject,
                                              //RelatedToId = lead.Id, // This throws error about not the expected type???
                                              TextBody = email.plainTextBody,
                                              HtmlBody = email.htmlBody,
                                              MessageIdentifier = email.messageId,
                                              ReplyToEmailMessageId = originalMessage.Id,
                                              ThreadIdentifier = originalMessage.ThreadIdentifier,
                                              Status = '3')); // Sets to replied.
            
            insert newEmail;
            // Add Email Message Relation to the lead because they sent it...
            EmailMessageRelation emr = new EmailMessageRelation();
            emr.emailMessageId = newEmail[0].Id;
            emr.relationAddress = email.fromAddress;
            emr.relationId = lead.id; // Lead Id
            emr.relationType = 'FromAddress';
            insert emr;
            
            EmailMessageRelation toEmr = new EmailMessageRelation();
            toEmr.emailMessageId = newEmail[0].Id;
            toEmr.relationAddress = lastUser.Email;
            toEmr.relationId = lastUser.Id; // User Id
            toEmr.relationType = 'ToAddress';
            insert toEmr;
            
            // Update the lead status to Patient Replied
            lead.status = 'Patient Replied';
            update lead;
            // The below was ripped from a forum https://developer.salesforce.com/forums/?id=906F00000008um5IAA, but I dont know if it works?
            // Add any binary attachments to the lead
            
            if(email.textAttachments != null)
            {
                // Save attachments, if any
                for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
                    Attachment attachment = new Attachment();
                    
                    attachment.Name = tAttachment.fileName;
                    attachment.Body = Blob.valueOf(tAttachment.body);
                    attachment.ParentId = lead.Id;
                    insert attachment;
                }
            }
            if(email.binaryAttachments != null && email.binaryAttachments.size() > 0){
                for(Messaging.InboundEmail.BinaryAttachment att : email.binaryAttachments){
                    system.debug('attachmentsList -> '+email.binaryAttachments);
                }
                List<ContentVersion>cvList = new List<ContentVersion>();
                List<ContentDocumentLink> cdlList = new List<ContentDocumentLink>();
                for (Messaging.InboundEmail.BinaryAttachment binAttach : email.binaryAttachments) {
                    ContentVersion testContentInsert = new ContentVersion();
                    testContentInsert.Title = binAttach.fileName;
                    testContentInsert.VersionData = binAttach.body;
                    testContentInsert.PathOnClient = '/' + binAttach.fileName ;
                    cvList.add(testContentInsert);
                    
                }
                insert cvList;
                cvList = [select id, ContentDocumentId from ContentVersion WHERE Id in :cvList];
                for (ContentVersion cv : cvList) {
                    ContentDocumentLink cl = new ContentDocumentLink();
                    cl.ContentDocumentId = cv.ContentDocumentId;
                    cl.LinkedEntityId = lead.id; //Shared with record ID
                    cl.ShareType = 'I';
                    cl.Visibility = 'AllUsers';
                    cdlList.add(cl);
                }
                insert cdlList;
            }else{
                system.debug('attachmentsList -> '+email.binaryAttachments);
            }
            
        }
        // If an exception occurs when the query accesses
        // the contact record, a QueryException is called.
        // The exception is written to the Apex debug log.
        catch (QueryException e) {
            System.debug('Query Issue: ' + e);
            System.debug('Query Issue: ' + e.getLineNumber());
            System.debug('Query Issue: ' + e.getCause());
            System.debug('Query Issue: ' + e.getTypeName());
            System.debug('Query Issue: ' + e.getMessage());
        }
        result.success = true;
        // return nothing...
        return result;
    }
}



Thank you
Sandeep. 
AnkaiahAnkaiah (Salesforce Developers) 
Hi Sandeep,

Refer the below link will help you proceed further on your test class.
https://developer.salesforce.com/forums/?id=9060G000000MQTIQA4

If this helps, Please mark it as best answer.

Thanks!!
Sandeep TechAffinitySandeep TechAffinity
Hi Ankaiah,

I have already tried this once still 16% coverage. Can you go through the class so you can get to know the issue?

Thank you
Sandeep