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
rmranjith8881.3927046400771116E12rmranjith8881.3927046400771116E12 

Test class for Custom Send an Email button !!!

Hi Everyone,

I have a Extensions on Oppportunity, which sends the Email with two Visualforce Pdf file attachments.
I need to write a test class for it,
As of now, My test coverage is 8%.
Please find my Code below.

Extensions and Test class Code:
 
//Send email with Multiple attachments, and before sending edit template
public class SendEmail {

    public Account acc;
    public String body { get; set; }    
    Product_EmailTemplates__c template;//Custom settings to read the template, which template to send
    public Opportunity opp { get; set;}
    public String subject { get; set; }
    public String htmlBody {get; set;}
    

    // Create a constructor that populates the Opportunity object
    public SendEmail(ApexPages.StandardController controller) {        
        opp = [Select Id, Name, Email__c, Amount, Contact_Name__c, Account.PersonContactId, Account.id, Product__r.Name, Account.Name, StageName, Tax_Amount__c, Total_after_Tax__c, 
               payment_1_Amount__c, Payment_2_Amount__c, Payment_3_Amount__c, Payment_1_Before_Tax__c, Payment_2_Before_Tax__c, Payment_3_Before_Tax__c, Payment_1_Tax_Amount__c, 
               Payment_2_Tax_Amount__c, Payment_3_Tax_Amount__c, Potential_Number__c,Branch_Name__c, Branch_Name__r.Name, Branch_Name__r.Address_1__c, Branch_Name__r.Address_2__c, Branch_Name__r.City__c, 
               Branch_Name__r.Country__c, Branch_Name__r.Main_Phone_1__c, Branch_Name__r.Main_Phone_2__c, Branch_Name__r.Main_Phone_3__c, Branch_Name__r.Region__c, Branch_Name__r.State__c, 
               Branch_Name__r.Zip_Postal_Code__c, Product__r.Product_Type__c, Admin_Fee__c, Payment_1_plus_Admin_Fee__c
                    from Opportunity where Id = :ApexPages.currentPage().getParameters().get('id')];
              
        EmailTemplate emailTemplate = [SELECT Id, Subject, HtmlValue, Body FROM EmailTemplate WHERE Id = :getTemplateId(opp.Product__r.Name, opp.Product__r.Product_Type__c)];
    
        htmlBody = emailTemplate.HtmlValue;
        subject = emailTemplate.subject;
    }
    
    //Send the email with two attachments
    public PageReference send() {
        // Define the email
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
        
        //Send email if Branch not equals to Saudi Arabia and Product type is Standard
        if(opp.Branch_Name__r.Name != 'Saudi Arabia' && opp.Product__r.Product_Type__c == 'Standard'){
            // Reference the attachment page and pass in the Opportunity ID
            PageReference pdf1 =  Page.CCLPdf;//CCLPdf is a Visualforce page
            pdf1.getParameters().put('id',opp.id); 
            pdf1.setRedirect(true);
    
            // Take the PDF content
            Blob b1 = pdf1.getContentAsPDF();
            
            PageReference pdf2 =  Page.ProformaInvoicePdf;//ProformaInvoicePdf is a Visualforce page
            pdf2.getParameters().put('id',opp.id); 
            pdf2.setRedirect(true);
    
            // Take the PDF content
            Blob b2 = pdf2.getContentAsPDF();
    
            // Create the email attachment
            Messaging.EmailFileAttachment efa1 = new Messaging.EmailFileAttachment();
            efa1.setFileName(opp.account.Name+'-CCL.pdf');//set the email attachment name
            efa1.setBody(b1);
            
            Messaging.EmailFileAttachment efa2 = new Messaging.EmailFileAttachment();
            efa2.setFileName(opp.account.Name+'-Invoice.pdf');//set the email attachment name
            efa2.setBody(b2);
            
            // Sets the paramaters of the email
            email.setSubject(subject);//Auto populate the Subject from Template
            email.setHtmlBody(htmlBody);//Auto populate the Body from Template
            //email.setTemplateId('00Xj0000000Yg9k');//getTemplateId(opp.Product__r.Name)
            email.setTargetObjectId(opp.Account.PersonContactId);
            email.setSaveAsActivity(true);
            email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa1,efa2});
            StoringAttachments();
        }
        
        //Send email if Branch not equals to Saudi Arabia and Product type is Canada
        if(opp.Branch_Name__r.Name != 'Saudi Arabia' && opp.Product__r.Product_Type__c == 'Canada'){
            // Reference the attachment page and pass in the Opportunity ID
            PageReference pdf3 =  Page.CANCCLPdf;//CANCCLPdf is a Visualforce page
            pdf3.getParameters().put('id',opp.id); 
            pdf3.setRedirect(true);
    
            // Take the PDF content
            Blob b3 = pdf3.getContentAsPDF();
            
            PageReference pdf4 =  Page.ProformaInvoicePdf;//ProformaInvoicePdf is a Visualforce page
            pdf4.getParameters().put('id',opp.id); 
            pdf4.setRedirect(true);
    
            // Take the PDF content
            Blob b4 = pdf4.getContentAsPDF();
    
            // Create the email attachment
            Messaging.EmailFileAttachment efa3 = new Messaging.EmailFileAttachment();
            efa3.setFileName(opp.account.Name+'-CANCCL.pdf');//set the email attachment name
            efa3.setBody(b3);
            
            Messaging.EmailFileAttachment efa4 = new Messaging.EmailFileAttachment();
            efa4.setFileName(opp.account.Name+'-CANInvoice.pdf');//set the email attachment name
            efa4.setBody(b4);
            
            // Sets the paramaters of the email
            email.setSubject(subject);//Auto populate the Subject from Template
            email.setHtmlBody(htmlBody);//Auto populate the Body from Template
            //email.setTemplateId('00Xj0000000Yg9k');//getTemplateId(opp.Product__r.Name)
            email.setTargetObjectId(opp.Account.PersonContactId);
            email.setSaveAsActivity(true);
            email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa3,efa4});
            StoringAttachments();
        }
        
        //Send email if Branch is saudi Arabia and Product type is Standard
        if(opp.Branch_Name__r.Name == 'Saudi Arabia' && opp.Product__r.Product_Type__c == 'Standard'){
            // Reference the attachment page and pass in the Opportunity ID
            PageReference pdf5 =  Page.KSACCLPdf;//KSACCLPdf is a Visualforce page
            pdf5.getParameters().put('id',opp.id); 
            pdf5.setRedirect(true);
    
            // Take the PDF content
            Blob b5 = pdf5.getContentAsPDF();
            
            PageReference pdf6 =  Page.ProformaInvoicePdf;//ProformaInvoicePdf is a Visualforce page
            pdf6.getParameters().put('id',opp.id); 
            pdf6.setRedirect(true);
    
            // Take the PDF content
            Blob b6 = pdf6.getContentAsPDF();
    
            // Create the email attachment
            Messaging.EmailFileAttachment efa5 = new Messaging.EmailFileAttachment();
            efa5.setFileName(opp.account.Name+'-KSACCL.pdf');//set the email attachment name
            efa5.setBody(b5);
            
            Messaging.EmailFileAttachment efa6 = new Messaging.EmailFileAttachment();
            efa6.setFileName(opp.account.Name+'-KSAInvoice.pdf');//set the email attachment name
            efa6.setBody(b6);
            
            // Sets the paramaters of the email
            email.setSubject(subject);//Auto populate the Subject from Template
            email.setHtmlBody(htmlBody);//Auto populate the Body from Template
            //email.setTemplateId('00Xj0000000Yg9k');//getTemplateId(opp.Product__r.Name)
            email.setTargetObjectId(opp.Account.PersonContactId);
            email.setSaveAsActivity(true);
            email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa5,efa6});
            StoringAttachments();
         } 
         
         //Send email if Branch is saudi Arabia and Product type is Canada
         if(opp.Branch_Name__r.Name == 'Saudi Arabia' && opp.Product__r.Product_Type__c == 'Canada'){
            // Reference the attachment page and pass in the Opportunity ID
            PageReference pdf7 =  Page.KSACANCCLPdf;//KSACANCCLPdf is a Visualforce page
            pdf7.getParameters().put('id',opp.id); 
            pdf7.setRedirect(true);
    
            // Take the PDF content
            Blob b7 = pdf7.getContentAsPDF();
            
            PageReference pdf8 =  Page.ProformaInvoicePdf;//ProformaInvoicePdf is a Visualforce page
            pdf8.getParameters().put('id',opp.id); 
            pdf8.setRedirect(true);
    
            // Take the PDF content
            Blob b8 = pdf8.getContentAsPDF();
    
            // Create the email attachment
            Messaging.EmailFileAttachment efa7 = new Messaging.EmailFileAttachment();
            efa7.setFileName(opp.account.Name+'-KSACANCCL.pdf');//set the email attachment name
            efa7.setBody(b7);
            
            Messaging.EmailFileAttachment efa8 = new Messaging.EmailFileAttachment();
            efa8.setFileName(opp.account.Name+'-KSACANInvoice.pdf');//set the email attachment name
            efa8.setBody(b8);
            
            // Sets the paramaters of the email
            email.setSubject(subject);//Auto populate the Subject from Template
            email.setHtmlBody(htmlBody);//Auto populate the Body from Template
            //email.setTemplateId('00Xj0000000Yg9k');//getTemplateId(opp.Product__r.Name)
            email.setTargetObjectId(opp.Account.PersonContactId);
            email.setSaveAsActivity(true);
            email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa7,efa8});
            StoringAttachments();
         } 
    
            // Sends the email
            Messaging.SendEmailResult [] r = 
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); 
        
        
        return new PageReference('/'+opp.Id);
    }
    
    //Creating attachments
    public void StoringAttachments() {
        //Send attachments if Branch is India and Product type is Standard
        if((opp.Branch_Name__r.Name == 'India' || opp.Branch_Name__r.Name == 'United Kingdom') && opp.Product__r.Product_Type__c == 'Standard'){
            Attachment myAttach1 = new Attachment();
            myAttach1.ParentId = opp.Account.PersonContactId;
            myAttach1.name = opp.account.Name+'-CCL.pdf';
            PageReference myPdf1 = Page.CCLPdf;
            myAttach1.body = myPdf1.getContentAsPdf();
            insert myAttach1;
            
            Attachment myAttach2 = new Attachment();
            myAttach2.ParentId = opp.Account.PersonContactId;
            myAttach2.name = opp.account.Name+'-Invoice.pdf';
            PageReference myPdf2 = Page.ProformaInvoicePdf;
            myAttach2.body = myPdf2.getContentAsPdf();
            insert myAttach2;
        }
        
        //Send attachments if Branch is India and Product type is Canada
        if((opp.Branch_Name__r.Name == 'India' || opp.Branch_Name__r.Name == 'United Kingdom') && opp.Product__r.Product_Type__c == 'Canada'){
            Attachment myAttach3 = new Attachment();
            myAttach3.ParentId = opp.Account.PersonContactId;
            myAttach3.name = opp.account.Name+'-CANCCL.pdf';
            PageReference myPdf3 = Page.CANCCLPdf;
            myAttach3.body = myPdf3.getContentAsPdf();
            insert myAttach3;
            
            Attachment myAttach4 = new Attachment();
            myAttach4.ParentId = opp.Account.PersonContactId;
            myAttach4.name = opp.account.Name+'-CANInvoice.pdf';
            PageReference myPdf4 = Page.ProformaInvoicePdf;
            myAttach4.body = myPdf4.getContentAsPdf();
            insert myAttach4;
        }
        
        //Send attachments if Branch is saudi Arabia and Product type is Standard
        if(opp.Branch_Name__r.Name == 'Saudi Arabia' && opp.Product__r.Product_Type__c == 'Standard'){
            Attachment myAttach5 = new Attachment();
            myAttach5.ParentId = opp.Account.PersonContactId;
            myAttach5.name = opp.account.Name+'-KSACCL.pdf';
            PageReference myPdf5 = Page.KSACCLPdf;
            myAttach5.body = myPdf5.getContentAsPdf();
            insert myAttach5;
            
            Attachment myAttach6 = new Attachment();
            myAttach6.ParentId = opp.Account.PersonContactId;
            myAttach6.name = opp.account.Name+'-KSAInvoice.pdf';
            PageReference myPdf6 = Page.ProformaInvoicePdf;
            myAttach6.body = myPdf6.getContentAsPdf();
            insert myAttach6;
        }
        
        //Send attachments if Branch is saudi Arabia and Product type is Canada
        if(opp.Branch_Name__r.Name == 'Saudi Arabia' && opp.Product__r.Product_Type__c == 'Canada'){
            Attachment myAttach7 = new Attachment();
            myAttach7.ParentId = opp.Account.PersonContactId;
            myAttach7.name = opp.account.Name+'-KSACANCCL.pdf';
            PageReference myPdf7 = Page.KSACANCCLPdf;
            myAttach7.body = myPdf7.getContentAsPdf();
            insert myAttach7;
            
            Attachment myAttach8 = new Attachment();
            myAttach8.ParentId = opp.Account.PersonContactId;
            myAttach8.name = opp.account.Name+'-KSACANInvoice.pdf';
            PageReference myPdf8 = Page.ProformaInvoicePdf;
            myAttach8.body = myPdf8.getContentAsPdf();
            insert myAttach8;
        }
    } 
    
    //Reads the Template from Custom settings        
    public String getTemplateId(String prodName, String prodType){
       template = [Select Name, Email_Template_Id__c, Product_Type__c from Product_EmailTemplates__c 
                        where Name = : prodName and Product_Type__c = : prodType];
       return template.Email_Template_Id__c;
   }

}

Test Class:

@isTest(seeAllData=true)
public class CreateCaseTests{

     private static Id leadId;

static testMethod void testCreateCase() {
    
        
        //Inserting Products
        Product2 prod = new Product2();
        prod.Name = 'Resident Visa';
        prod.ProductCode = 'RV';
        insert prod;
        
        //Inserting Products
        Product2 prod1 = new Product2();
        prod1.Name = 'Permanant Visa';
        prod1.ProductCode = 'PV';
        insert prod1;
        
        //get standard pricebook
        Pricebook2  standardPb = [select Id, Name, isActive from Pricebook2 where IsStandard = true limit 1];
        
        //Inserting pricebook
        Pricebook2 pb = new Pricebook2();
        pb.Name = 'India';
        pb.IsActive= true;
        insert pb;
        
        //Inserting pricebook
        Pricebook2 pb1 = new Pricebook2();
        pb1.Name = 'Saudi Arabia';
        pb1.IsActive= true;
        insert pb1;
        
        //Inserting pricebookEntry
        PricebookEntry pbe = new PricebookEntry();
        pbe.Pricebook2Id = standardPb.Id;
        pbe.Product2Id = prod.Id;
        pbe.UnitPrice = 1.0;
        //pbe.UseStandardPrice = true;
        pbe.IsActive = true;
        insert pbe;
        
        //Inserting pricebookEntry
        PricebookEntry pbe1 = new PricebookEntry();
        pbe1.Pricebook2Id = standardPb.Id;
        pbe1.Product2Id = prod1.Id;
        pbe1.UnitPrice = 1.0;
        //pbe.UseStandardPrice = true;
        pbe1.IsActive = true;
        insert pbe1;
        
        Lead testLead = new Lead();
            testLead.FirstName = 'Test First';
            testLead.LastName = 'Test Last';
            //testLead.Company = 'Test Co';
            //testLead.RecordTypeId = '012110000004b9Q';
            testLead.Status = 'Converted';
            testLead.LeadSource = 'Web';
            testLead.Date_Received__c = System.Today();
            testLead.Email = 'ranjith@rixyncs.co.in';
            testLead.Payment_Plan__c = '2 Monthly Payments';
            testLead.Phone = '+919590854842';
            testLead.MobilePhone = '+919590854842';
            //testLead.Branch__c = 'India';
            testLead.CurrencyIsoCode = 'INR';
            testLead.Destination_Visa__c = 'Denmark';
            testLead.Product__c = prod.Id;
            testLead.Date_of_Birth__c = System.Today();
            testLead.Age__c = 30;
            testLead.Occupation__c = 'SE';
            testLead.Number_of_years_in_this_occupation__c = 2;
            testLead.Highest_Qualification__c = 'MCA';
            testLead.Experience__c = 'Full - Time';
            testLead.Dependents__c = '2';
            testLead.Nationality_Immigration_Status__c = 'Pending';
            testLead.Criminal_Health__c = 'No';
            testLead.Job_Offer__c = True;
            testLead.Maintenance__c = 'Yes';
            testLead.Family_Links__c = True;
            testLead.Country = 'India';
            testLead.Country__c = 'India';
            insert testLead;
            leadId = testLead.Id;
            
            System.currentPagereference().getParameters().put('id',testLead.id);

        
        
        
        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(leadId);
        //lc.setAccountId(myRecordType.Id) ;
        //lc.strAccountId= '1';
        //lc.strContactId= '1';
        LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        
        Database.LeadConvertResult lcr = Database.convertLead(lc);
        //lcr.getAccountId();
        //lcr.getContactId();
        //lcr.getOpportunityId();
        
        //this line returned my lead with isConverted:true and ids for related contact and account
    /*Lead leadFromDB = [select 
                       FirstName,
                       LastName,
                       Country,
                       isConverted,
                       ConvertedAccountId,
                       ConvertedContactId
                       from Lead where id = : testLead.Id];
    System.debug('this lead looks like: ' + leadFromDB);

    // successfully queried contact, would produce query exception if no contact found
    Contact c = [select Id,FirstName,LastName from Contact where Id = : leadFromDB.ConvertedContactId];

    // again success, no query exception
    Account a = [select Id,Name from Account where Id = : leadFromDB.ConvertedAccountId];

    // confirmation in my log of what I got back.
    System.debug(c);
    System.debug(a);*/

    //System.assert(lcr.isSuccess()); //<--assert passed   
        
        System.assert(lcr.isSuccess());
        

    
        /*Inserting Lead and converting
        Lead ld = new Lead();
        ld.LastName='Doe';
        ld.FirstName='John';
        ld.Company='Test';
        ld.Status = 'Converted';
        ld.LeadSource = 'Web';
        ld.Date_Received__c = System.Today();
        ld.Email = 'ranjith@rixyncs.co.in';
        ld.Payment_Plan__c = '2 Monthly Payments';
        ld.Phone = '+919590854842';
        ld.MobilePhone = '+919590854842';
        ld.Branch__c = 'India';
        ld.CurrencyIsoCode = 'INR';
        ld.Destination_Visa__c = 'Denmark';
        ld.Product__c = prod.Id;
        ld.Date_of_Birth__c = System.Today();
        ld.Age__c = 30;
        ld.Occupation__c = 'SE';
        ld.Number_of_years_in_this_occupation__c = 2;
        ld.Highest_Qualification__c = 'MCA';
        ld.Experience__c = 'Full - Time';
        ld.Dependents__c = '2';
        ld.Nationality_Immigration_Status__c = 'Pending';
        ld.Criminal_Health__c = 'No';
        ld.Job_Offer__c = True;
        ld.Maintenance__c = 'Yes';
        ld.Family_Links__c = True;
        insert ld;            


        ld =  [SELECT Id,Status, FirstName,LastName,Company,LeadSource
             FROM Lead
             WHERE Id = :ld.Id];

        System.assertEquals('Converted', ld.Status);*/
        
        RecordType myRecordType = [select id from RecordType where SobjectType='Account' AND IsPersonType=True limit 1];
    
        //Inserting Account
        Account acc = new Account();
        acc.LastName = 'Ranjith';
        acc.RecordTypeId = myRecordType.Id;
        insert acc;
        
        //Inserting Contact
        Contact con = new Contact();
        con.LastName = 'kumar';
        //con.AccountId = acc.Id;
        insert con;    
              
                
        
        
        //Inserting Potential
        Opportunity opp = new Opportunity();
        opp.Name = 'Ranjith kumar';
        //opp.Potential_Number__c = '0011';
        opp.AccountId = acc.Id;
        opp.CloseDate = System.today()+20;
        opp.StageName = 'CCL Sent';
        opp.Contact_Name__c = con.Id;
        opp.Type  = 'Existing Business';
        opp.English_Language__c  = 'Vocational';
        opp.Payment_Plan__c = '2 Monthly Payments';
        opp.Tax_Amount__c = 1000.00;
        opp.Total_after_Tax__c = 1000000.00;
        opp.Amount = 10000000.00;
        opp.Date_of_Birth__c = System.today();
        opp.Destination_Visa__c = 'US';
        opp.TimeFrame__c = '3 Months';
        opp.Eligibility_Score__c = 60;
        //opp.Branch__c = 'India';
        opp.Occupation__c = 'SE';
        opp.Number_of_years_in_this_occupation__c = 2;
        opp.Highest_Qualification__c = 'MCA';
        opp.Experience__c = 'Full - Time';
        opp.Dependents__c = '2';
        opp.Nationality_Immigration_Status__c = 'Pending';
        opp.Criminal_Health__c = 'No';
        opp.Job_Offer__c = True;
        opp.Maintenance__c = 'Yes';
        opp.Family_Links__c = True;
        opp.payment_1_Amount__c = 100.00;
        opp.Payment_2_Amount__c = 100.00;
        opp.Payment_3_Amount__c = 100.00;
        opp.Payment_1_Received_Date__c = System.today();
        opp.Payment_2_Due_Date__c = System.today()+30;
        opp.Payment_3_Due_Date__c = System.today()+60;
        opp.Payment_1_Before_Tax__c = 100.00;
        opp.Payment_2_Before_Tax__c = 100.00;
        opp.Payment_3_Before_Tax__c = 100.00;
        opp.Payment_1_Status__c = 'Received';
        opp.Payment_2_Status__c = 'Pending';
        opp.Payment_3_Status__c = 'Pending';   
        opp.Pricebook2Id  = pbe.Pricebook2Id; 
        opp.Product__c = prod.Id;
        insert opp;
    System.currentPagereference().getParameters().put('id',opp.id);
         Blob content;        
         PageReference pf = page.CCLPdf;
         Attachment objAtt = new Attachment();
         objAtt.Name = opp.Account.Name + '-CCL.Pdf';
         objAtt.body =  Blob.valueof('string');
         objAtt.ParentId = opp.Id;        
         if (Test.IsRunningTest()){
                content=Blob.valueOf('UNIT.TEST');
             }else{
                content=pf.getContent();
             }
         insert objAtt;
        
ApexPages.StandardController stdController = new ApexPages.StandardController(opp); 
        SendEmail send = new SendEmail(stdController);
        
        send.send();
        send.StoringAttachments();
        send.getTemplateId('Permanant Visa','Standard');
        
    
      }
    
}


Can anyone please help me to write a Test class for my Extensions?

Thanks In Advance.......
Ranjith

 
SonamSonam (Salesforce Developers) 
Hi Ranjith, 

Did you try running this test class in the developer console? it will give you the lines which are tested and the ones that still remain to be tested and will make it easier for you to write the test class.

Also, to cover the lines where you are sending custom email, check the code on the link:http://salesforce.stackexchange.com/questions/45365/test-class-is-not-covering-email-messaging