Email Services Test Classes

Apex Feb 12, 2015

On How to Set Up Email Services in Salesforce <a href=""https://developer.salesforce.com/page/An_Introduction_To_Email_Services_on_Force.com target="_blank">Click Here.

So following in Full Pledged Test Class for Email Services in Salesforce, please check out

Test Class

@IsTest
private class EmailService_Test {
        // Create a new email and envelope object (Mandatory)
        Messaging.InboundEmail email  = new Messaging.InboundEmail();
        Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
                
        // Create the email body
        email.plainTextBody = 'This should become a note';
        email.fromAddress ='test@test.com';
        String contactEmail = 'test@domain.com';
        email.ccAddresses = new String[] {'Test Domain <' + contactEmail + '>'};
        email.subject = 'Dummy Subject';
        
        EmailDemoReceive edr = new EmailDemoReceive();
        
        Test.startTest();
        // pass email & enveloper object as parameters here
        Messaging.InboundEmailResult result = edr.handleInboundEmail(email, env);
        Test.stopTest();
        
        System.assert (result.success, 'InboundEmailResult returned a failure message');
        
        Account [] accDb = [select ID from Account where name=:email.subject];
        System.assertEquals (1, accDb.size(),'Account was not inserted');
        Contact [] cDb = [select firstname,lastname from Contact where email=:contactEmail];
        System.assertEquals (1, cDb.size(),'Contact was not inserted!');
        Contact c = CDb[0];
        System.assertEquals ('Test', c.firstName);
        System.assertEquals ('Domain', c.LastName);
        Note [] nDb = [select body from Note where ParentID=:accDb[0].id];
        System.assertEquals (1,nDb.size(), 'A note should have been attached');
        System.assertEquals (email.plainTextBody, nDb[0].body);
        
    } 
}

If you any doubts please comment in below box

Happy coding!!!

Phanindra Mangipudi

Salesforce, Lightning Web Componets, Node.Js, Angular 2+, Bootstrap