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
sfdc G 9sfdc G 9 

Please help me to write test class for this.

Description: When closing a case an email should trigger. need test class for this.

public class SendCasePrintableViewAsPDF extends AbstractTriggerHandler {
    public override void afterUpdate() {
        
        Set<Id> closedCaseIds = new Set<Id>();
        Map<Id, Case> oldCaseMap = (Map<Id, Case>)Trigger.oldMap;
        
        // Retrieve the custom label value containing the desired Record Type Developer Names.
    String customLabelValue = Label.CaseArchive_RecordType;
    List<String> desiredRecordTypes = customLabelValue.split(';');
        
        for (Case updatedCase : (List<Case>)Trigger.New) {
            system.debug('updatedCase.RecordType.DeveloperName===='+updatedCase.RecordTypeId);
            system.debug(updatedCase.RecordTypeid);
            Case oldCase = oldCaseMap.get(updatedCase.Id);
            if(updatedCase.IsClosed && !oldCase.IsClosed && desiredRecordTypes.contains(updatedCase.RecordTypeId)){
                system.debug('insideRT=======');
                closedCaseIds.add(updatedCase.Id);
            }
        }
        sendPDF(closedCaseIds);
    }

    @future(callout=true)
    private static void sendPDF(Set<Id> closedCaseIds) {
        // Define the email address where the PDF will be sent
        String recipientEmail = Label.CaseArchive_Email;
        
        // Query the necessary Case data and related records outside the loop
        List<Case> closedCases = [SELECT Id, Subject, Casenumber, origin, owner.name, ownerid, Description,Account.Name, Contact.Name
                                  FROM Case WHERE Id IN :closedCaseIds];

        // Generate the PDF for each closed case and send the email
        for (Case closedCase : closedCases) {
            // Generate the PDF content
            PageReference printablePage = Page.SendCasePrintableViewAsPDF; // Visualforce Page
            printablePage.getParameters().put('id', closedCase.Id);
            Blob pdfBlob;
            try {
                pdfBlob = printablePage.getContentAsPDF();
            } catch (VisualforceException e) {
                // Error handling for Vf page
                System.debug('Error generating PDF: ' + e.getMessage());
                continue;
            }

            // Create and send the email
            List<Messaging.SingleEmailMessage> emailMessagesList = new List<Messaging.SingleEmailMessage>(); 
            Messaging.SingleEmailMessage emailMessage = new Messaging.SingleEmailMessage();
            emailMessage.setToAddresses(new String[] { recipientEmail });
            emailMessage.setSubject(closedCase.CaseNumber + '-' + closedCase.Subject);
            String plainTextBody = '';
            plainTextBody += 'Case Number : '+ closedCase.CaseNumber +'\n';              
            plainTextBody += 'Case Origin : '+ closedCase.origin +'\n';
            plainTextBody += 'Case Owner : '+ closedCase.Owner.Name +'\n';
            plainTextBody += 'Subject : '+ closedCase.Subject +'\n';
            plainTextBody += 'Description : '+ closedCase.Description +'\n';
            plainTextBody += 'Contact Name : '+ closedCase.Contact.Name +'\n';
            plainTextBody += 'Account Name : '+ closedCase.Account.Name +'\n';
            emailMessage.setPlainTextBody(plainTextBody);
            emailMessage.setFileAttachments(new Messaging.EmailFileAttachment[] {
                new Messaging.EmailFileAttachment()
            });
            emailMessage.getFileAttachments()[0].setFileName('Case Number: ' + closedCase.CaseNumber + '.pdf');
            emailMessage.getFileAttachments()[0].setBody(pdfBlob);

            // Send the email
            emailMessagesList.add(emailMessage);
            Messaging.sendEmail(emailMessagesList, False);
            //Messaging.sendEmail(new Messaging.SingleEmailMessage[] { emailMessage });
        }
    }
}
SwethaSwetha (Salesforce Developers) 
HI ,

To create a test class for the SendCasePrintableViewAsPDF class, you'll need to cover the logic inside the afterUpdate() and sendPDF() methods. Since the sendPDF() method is annotated as @future(callout=true), you need to use the Test.startTest() and Test.stopTest() methods to invoke future methods within the test context.

Example code:
@isTest
public class TestSendCasePrintableViewAsPDF {
    @isTest
    static void testSendPDF() {
        // Create a test Case with the desired record type and other necessary fields
        Case testCase = new Case(
            Subject = 'Test Case',
            Description = 'This is a test case.',
            Origin = 'Email', // Set to the appropriate origin value
            Status = 'Closed', // Make sure the status is 'Closed' for afterUpdate logic
            RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Your_Desired_Record_Type').getRecordTypeId()
        );
        insert testCase;

        // Set custom labels used in the class
        Test.setFixedSearchResults(new List<Id>{testCase.Id}); // Set the query result for closedCases query
        Test.setFixedSearchResults(new List<Id>{}); // Set the query result for User query (recipientEmail)

        // Call the method to trigger the future callout
        Test.startTest();
        SendCasePrintableViewAsPDF.sendPDF(new Set<Id>{testCase.Id});
        Test.stopTest();

        // Verify that the email was sent
        List<Messaging.SingleEmailMessage> sentEmails = [SELECT Id FROM Messaging.SingleEmailMessage];
        System.assertEquals(1, sentEmails.size());
    }
}

Replace 'Your_Desired_Record_Type' with the actual Developer Name of the desired record type that should trigger the email. Also, the Test.setFixedSearchResults method is used to set the query results for specific queries inside the future method. Make sure to set them with appropriate data for your test scenario.

If this information helps, please mark the answer as best. Thank you
Naresh Kaneriya 9Naresh Kaneriya 9
HI @sfdc G 9

test class for your SendCasePrintableViewAsPDF class. This test class is designed to provide coverage for the sendPDF method:

@isTest
private class SendCasePrintableViewAsPDFTest {
    @isTest
    static void testSendPDF() {
        // Create test data - you might need to adjust this based on your specific schema
        Account testAccount = new Account(Name = 'Test Account');
        insert testAccount;

        Contact testContact = new Contact(FirstName = 'Test', LastName = 'Contact', AccountId = testAccount.Id);
        insert testContact;

        Case testCase = new Case(Subject = 'Test Case', Origin = 'Web', AccountId = testAccount.Id, ContactId = testContact.Id);
        insert testCase;

        Set<Id> closedCaseIds = new Set<Id>();
        closedCaseIds.add(testCase.Id);

        Test.startTest();
        // Call the sendPDF method
        SendCasePrintableViewAsPDF.sendPDF(closedCaseIds);
        Test.stopTest();

        // Add assertions as needed
        // For example, you can assert that an email was sent, but note that it's not possible to directly test the actual email content or attachment in Apex tests.
        // You can check if the Messaging.sendEmail method was called and assertions on email logs in a real-world scenario.

        // You can also add assertions on the Case, Contact, Account records as needed.
    }
}



You can add some more test data to cover you apex class coverage.