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
Harjeet Singh 13Harjeet Singh 13 

Test Class SingleEmailMessaging

Hi Everyone,

I need a test class code which covers the below lines of code:
I am unable to cover the code for exception mail code
/* @purpose : Send the exception email to the user who started the batch job
    */    
    public static void sendExceptionEmail(Exception e) {
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.setTargetObjectId(UserInfo.getUserId());
        message.subject = 'Batch job failed to create Pickup request on ' + System.now().format('MM/dd/yyyy HH:mm:ss');
        message.saveAsActivity = FALSE;
        message.plainTextBody = 'Exception while creating Pickup requests ' + e.getMessage() + '\n' + e.getStackTraceString();
        Messaging.SingleEmailMessage[] messages = 
            new List<Messaging.SingleEmailMessage> {message};
                Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
    }

Kindly help me

Thanks & Regards,
Harjeet
Best Answer chosen by Harjeet Singh 13
PawanKumarPawanKumar
Okay.

Now what i would suggest that you can add below test method  in your existing test class and replace the class "EmailServiceUtil" with your class name where method exist "sendExceptionEmail()". In this way, overall you will get coverage for this code as well.

@IsTest
 static void testSendExceptionEmail() {
  DMLException dmlEx = new DMLException('Test Ex Email');
  EmailServiceUtil.sendExceptionEmail(dmlEx);
// Just repace "EmailServiceUtil" with your class name.
 }

Regards,
Pawan Kumar

All Answers

PawanKumarPawanKumar
Hi Harjit,
It is always difficult to teset email. So You will have to create separte class for your email and then write test class in order to get code coverage as below.

// Email Class
Public class EmailServiceUtil {

 public static void sendExceptionEmail(Exception e) {
  Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
  message.setTargetObjectId(UserInfo.getUserId());
  message.subject = 'Batch job failed to create Pickup request on ' + System.now().format('MM/dd/yyyy HH:mm:ss');
  message.saveAsActivity = FALSE;
  message.plainTextBody = 'Exception while creating Pickup requests ' + e.getMessage() + '\n' + e.getStackTraceString();
  Messaging.SingleEmailMessage[] messages =
   new List < Messaging.SingleEmailMessage > {
    message
   };
  Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
 }
}

// Test Class
@IsTest
Public class EmailServiceUtilTest {

 @IsTest
 static void testSendExceptionEmail() {
  DMLException dmlEx = new DMLException('Test Ex Email');
  EmailServiceUtil.sendExceptionEmail(dmlEx);

 }

}

Please let me know if it helps you.

Regards,
Pawan Kuar
Harjeet Singh 13Harjeet Singh 13
Thanks alot pawan for your response.

But the thing is I can't write separate class for email class. sendExceptionEmail method is a part of class and the class was written by some other developer and I am trying to increase the code coverage. But not able to cover a single line of the sendExceptionEmail method

Kindly let me know how can I include the test coverage for the same in one test class where I wrote the test method for other class methods

Thanks & Regards,
Harjeet
PawanKumarPawanKumar
Okay.

Now what i would suggest that you can add below test method  in your existing test class and replace the class "EmailServiceUtil" with your class name where method exist "sendExceptionEmail()". In this way, overall you will get coverage for this code as well.

@IsTest
 static void testSendExceptionEmail() {
  DMLException dmlEx = new DMLException('Test Ex Email');
  EmailServiceUtil.sendExceptionEmail(dmlEx);
// Just repace "EmailServiceUtil" with your class name.
 }

Regards,
Pawan Kumar
This was selected as the best answer
Harjeet Singh 13Harjeet Singh 13
Thanks Pawan once again. I already tried what you have replied.But still not a single line is getting covered for sendExceptionEmail method.
Really I need a help

Thanks & Regards,
Harjeet
Harjeet Singh 13Harjeet Singh 13
Oh my bad...

Thanks pawan you resolved my issue. Thanks a lot.
Actually I didnt mentioned testMethod instead simply copied pasted your code and replace with my code. Once I add testMethod keyword and ran MAGIC happened. All the lines of the codes got covered.

I really appreaciate your kind help

Thanks & Regards,
Harjeet
PawanKumarPawanKumar
Great to know. Please give me a favour by marking best answer.
 
JessFeauJessFeau
global with sharing class DocumentQuoteEmailController {


    public String email { get; set; }
    public Attachment attachment;
    public String quoteId;
    public Quote qte;

     public DocumentQuoteEmailController(ApexPages.StandardController controller) {
        this.qte=(Quote)controller.getRecord();
        quoteId = qte.id;
                this.qte=(Quote)controller.getRecord();
    }  

  String parameterValue = ApexPages.currentPage().getParameters().get('Id');    //this generates the record Id of the quote  
    


public Quote abc = [SELECT Id, Color__c FROM Quote WHERE Id=:parameterValue];//this generates the Assay type from the Quote
String q = abc.Color__c;//this converts the color to a string so it can be compared to  

Quote efg = [SELECT Id, Sponsor_s_of_Won_Proposals__c FROM Quote WHERE Id=:parameterValue];//this generates the #of won proposals for sponsor from the Quote
Decimal wonproposals = efg.Sponsor_s_of_Won_Proposals__c;//this converts the number of won proposals type to a string so it can be compared 

Quote hij = [SELECT Id, Sponsor_Email__c FROM Quote WHERE Id=:parameterValue];//this generates the email sponsor from the Quote
String sponsoremail = hij.Sponsor_Email__c;//this converts the email to a string

Contact qrs =[SELECT Id, Email FROM Contact WHERE Email=:sponsoremail];//finds the Contact where the email =the sponsor email selected for the quote
 Id targetObjectId=qrs.Id  ; //calcualates the Id for use in Set Target Object ID to send the email to
 
 Quote tuv = [SELECT Id, Is_Proposal_a_Change_Order__c FROM Quote WHERE Id=:parameterValue];//this generates the eIs Proposal a Change ORder field
String typeofproposal = tuv.Is_Proposal_a_Change_Order__c;//this tells if it is a change order

  public PageReference sendDoc() {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setUseSignature(false);
  if (email=='') {}
  else{     mail.setToAddresses(new String[] { email });}

        
Quote oppowner = [SELECT Id, Owner_Email__c from Quote WHERE Id=:parameterValue]; //gets the owner email of the quote
String oppowneremail = oppowner.Owner_Email__c;
String[] ccAddresses = new String[] {oppowneremail};
        mail.setCcAddresses(ccAddresses);
        
        OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = :oppowneremail];
if ( owea.size() > 0 ) {
    mail.setOrgWideEmailAddressId(owea.get(0).Id);
}


        mail.setWhatId(quoteId);
        
        if(typeofproposal=='Change Order'){
        mail.setTemplateId('00X0n000000DmBO');}
        
       else if ((q =='red'||q =='pink'||q =='orange')&&wonproposals<2){
        mail.setTemplateId('00X0n000000Dlrs');}//sets the reddish template if Color is =reddish and Sponsor is new
        
       else if ((q =='red'||q =='pink'||q =='orange')&&wonproposals>1){
        mail.setTemplateId('00X0n000000Dm4I');}//sets the reddish template if Color is =reddish and Sponsor is old
        
        else if ((q =='blue')&&wonproposals<2){
        mail.setTemplateId('00X0n000000Dm3y');}//sets the blue template if Color is =blue and Sponsor is new
        
         else if ((q =='blue')&&wonproposals>1){
        mail.setTemplateId('00X0n000000Dm4D');}//sets the blue template if Assay_from_Op is =LC and Sponsor is old
        
       else if ((q =='yellow'||q =='sunflower'||q =='bumble bee'||q =='gold'||q =='maize')&&wonproposals<2){
        mail.setTemplateId('00X0n000000M6BU');}//sets the yellow template if Color is =yellow and Sponsor is new 
        
       else if ((q =='yellow'||q =='sunflower'||q =='bumble bee'||q =='gold'||q =='maize')&&wonproposals>1){
        mail.setTemplateId('00X0n000000Dm4S');}//sets the LBA template if Color is =yellow and Sponsor is old
        
       else{mail.setTemplateId('00X0n000000Dm4S');}//sets the reddish old template (which is currently the same as all old templates) as default if not equal to any above criteria
       
        mail.settargetobjectid(targetObjectId);//sets who we send to

        List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
        for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :quoteId AND CreatedDate = Today AND ContentType='application/pdf' AND Name LIKE '%Study Number%']) {  // Add to attachment file list  
            Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();  
            efa.setFileName(a.Name); 
            efa.setBody(a.Body); 
            fileAttachments.add(efa);
        }
        mail.setFileAttachments(fileAttachments);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
 
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Email with Attachment sent to '+email +' ' +oppowneremail +' and ' +sponsoremail));   
    
        return null;
    }
    
  


       
}
Can anyone help me with the test class for above?  I have tried the test class below and keep having issues
@IsTest
 static void testDocumentQuoteEmailController() {
  PageReference pageref = new PageReference();
  DocumentQuoteEmailController.sendDoc(pageref);
// Just repace "EmailServiceUtil" with your class name.
 }