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
enahijenahij 

Test class for sending emails with attachement

Hello, can you please help me a test class for this class.
I tried to write one but I always have 0% coverage.
Any help or suggestions please.

public without sharing class SendEmaile { 
    public class Params { 
        @InvocableVariable 
        public String template; 
        @InvocableVariable
        public String orgWideEmailAddress; 
        @InvocableVariable 
        public String toAddress; 
        @InvocableVariable 
        public Id contactId; 
        @InvocableVariable
        public Id recordId; 
        @InvocableVariable
        public Id relatedId; 
        @InvocableVariable
        public Boolean sendAttachment; 
    } 

    @InvocableMethod 
    public static void sendEmail(List<Params> requests) { 
        try { 
            Params request = (requests.size() == 1) ? requests[0] : null; 
            if (request != null) { 
                // Get Content Document Ids 
                Set<String> contentDocumentIds = new Set<String>(); 
                List<ContentDocumentLink> cdls = [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :request.recordId]; 
                for (ContentDocumentLink doc : cdls) { 
                    contentDocumentIds.add(doc.ContentDocumentId); 
                } 
                EK_Parameter__mdt noReplyEmail = EK_Parameter__mdt.getInstance('Facture');
               // Get Email Template 
                Id templateId = [SELECT Id FROM EmailTemplate WHERE DeveloperName = 'Interv'].Id; 
                // New email message 
                Messaging.SingleEmailMessage mail = Messaging.renderStoredEmailTemplate(templateId, null, request.relatedId); 
                // Set OrgWideEmailAddress Id 
                Id orgWideEmailAddressId = [SELECT Id FROM OrgWideEmailAddress WHERE Address =: noReplyEmail.Value__c LIMIT 1].Id; 
                if (orgWideEmailAddressId != null) { 
                    mail.setOrgWideEmailAddressId(orgWideEmailAddressId); 
                } 
                // Set Email Properties 
                mail.toAddresses = new String[]{request.toAddress}; 
                mail.setTargetObjectId(request.contactId); 
                mail.setWhatId(request.relatedId); 
                mail.setTreatTargetObjectAsRecipient(false); 
                mail.setTreatBodiesAsTemplate(false); 
                // Set Email Attachments 
                if (request.sendAttachment == true) { 
                    List<ContentVersion> contentVersionFile = [SELECT VersionData, Title, FileType FROM ContentVersion WHERE ContentDocumentId IN :contentDocumentIds AND IsLatest = true]; 
                    List<Messaging.EmailFileAttachment> emailFileAttachments = new List<Messaging.EmailFileAttachment>(); 
                    for (ContentVersion cv : contentVersionFile) { 
                        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment(); 
                        efa.setFileName(cv.Title + '.' + cv.FileType); 
                        efa.setBody(cv.VersionData); 
                        emailFileAttachments.add(efa); 
                    } 
                    if (!emailFileAttachments.isEmpty()) { 
                        mail.setFileAttachments(emailFileAttachments); 
                    } 
                } 
                // Send Email 
                Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage>{mail}; 
                if (!Test.isRunningTest()) { 
                    Messaging.SendEmailResult[] results = Messaging.sendEmail(messages); 
                    if (results[0].success) { 
                        System.debug('The email was sent successfully.'); 
                    } else { 
                        System.debug('The email failed to send: ' + results[0].errors[0].message); 
                    } 
                } 
            } 
        } catch (Exception e) { 
            throw new SendEmailException(e.getMessage(), e); 
        } 
    } 
    /** 
     * EXCEPTIONS 
     */ 
    public class SendEmailException extends Exception { } 
}
Dilan KoleDilan Kole
Great you have did an amazing work. I tested the script for emails of castle crush (https://apkdudes.com/bad-piggies-hd-mod-apk/) and its working fine. I have save the script with myself and will use it for my next comming projects.
CharuDuttCharuDutt
Hii Enahji
Try Below Test Class 87%Coverage
@isTest
public class SendEmaileTest {
	@isTest
    public static void unitTest(){
        Account Acc = new Account();
        Acc.Name = 'Test';
        insert Acc;
        Contact Con = new Contact();
        Con.FirstName = 'Test';
        Con.LastName = 'Contact';
        Con.AccountId = Acc.id;
        con.Email = 'test123@test.com';
        insert Con;
        
        Blob bodyBlob=Blob.valueOf('Unit Test ContentVersion Body to be insert in test class for testing the'); 
            
            ContentVersion contentVersion_1 = new ContentVersion(
                Title='SampleTitle', 
                PathOnClient ='SampleTitle.jpg',
                VersionData = bodyBlob, 
                origin = 'H'
            );
            insert contentVersion_1;
            
            ContentVersion contentVersion_2 = [SELECT Id, Title, ContentDocumentId 
                            FROM ContentVersion WHERE Id = :contentVersion_1.Id LIMIT 1];
            
            ContentDocumentLink contentlink = new ContentDocumentLink();
            contentlink.LinkedEntityId = acc.id;
            contentlink.contentdocumentid = contentVersion_2.contentdocumentid;
            contentlink.ShareType = 'V';
            insert contentlink;
        
        
        
        
        
        list<SendEmaile.Params> lstse= new list<SendEmaile.Params>();
        SendEmaile.Params se= new SendEmaile.Params();
        se.contactId =con.Id;
        se.recordId = Acc.Id;
        se.relatedId = Con.Id;
        se.toAddress = con.Email;
        se.sendAttachment = true;
        lstse.add(se);

        SendEmaile.sendEmail(lstse);
    }
}
Pleae Mark It As Best Answer If It Helps
Thank You!
Joany ReichertJoany Reichert
I am pretty green in APEX, but was tasked to write a class and subsequent test class for a daily inbound email to load to an object with raw call log data. I am getting 52% coverage on the test and the main area it is failing is in the area in the picture I have loaded MyIndigo Card (https://www.myindigocard.bid/)