• lazy coder
  • NEWBIE
  • 0 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 2
    Replies

Hello All,

I have been struggling with my APEX code to delete Shipment records then send and email. The APEX code works correctly when tested and receive the email with results, however I cannot get above 66% Code Coverage when I test. Lines in BOLD are not code covered? I am losing my mind and my boss is angry. Please Help.

With thanks in advance.

Robert

 

/*
* Description   : This is Batch to Perform delete operation on Shipment Records.
*
*                 Shipments are Deletable when Shipment is 42 days or older.
*                 Formula "TODAY() > Date__c + 42" sets Deletable__c = TRUE

* Created By    : Robert Wambold
*
* Created Date  : 08/09/2018
*
* Version       : v1.0 - Create 
*/

//Batch Class
global class Batch_ShipmentDelete implements Database.Batchable<sObject>,Database.stateful {
  
  //Variable to count Success and Error Records
    public Integer successCounter = 0;
    public Integer failureCounter = 0; 
         
    //Start Method 
    global Database.QueryLocator start(Database.BatchableContext BC) { 
    
        //Query to Fetch Records
        return Database.getQueryLocator([SELECT ID FROM Shipment__c WHERE Deletable__c = TRUE]);
   
    }
    
    //Execute Method
    global void  execute(Database.BatchableContext BC, List<Shipment__C> scope) {
      
    //Delete the Records those are in Contexts
        Database.DeleteResult[] delresults = Database.delete((scope),false);
        
        //Loop through records going to be deleted
        for(Database.DeleteResult dr : delResults){
        
            //If record is not successfully deleted
            if(!dr.isSuccess()){
            
                //List to hold Error
                Database.Error[] errs = dr.getErrors();
                
                //Loop through list of Error
                for(Database.Error err : errs) {
                    
                    //Debug to get Error Status
                    System.debug('$#$#$#$' + err.getStatusCode() + ' - ' + err.getMessage());
                    
                    //Debug to get Error Message
                    System.debug('ErrorMessage##########'+ err.getMessage());
                }
                
                //Increase counter for Failure
                 failureCounter++;
            }
            
            else {
            
                successCounter++;
            }
        }      
    }
    
    //Finish Method
    global void finish(Database.BatchableContext BC){
      
      // Query the AsyncApexJob object to retrieve the current job's information.
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
        TotalJobItems, CreatedBy.Email
        FROM AsyncApexJob WHERE Id = :BC.getJobId()];
        
        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Apex Shipment Delete Job ' + a.Status);
        mail.setPlainTextBody
        ('Apex Shipment Delete Job has been completed. There were total of ' + a.TotalJobItems 
              + ' batches with ' + successCounter + ' success and ' + failureCounter
              + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
    }
}

 

My Test Code

@IsTest
public class Batch_ShipmentDeleteTEST
{
    //Database.Error[] errs = dr.getErrors();
 static testMethod void testMethod1()
 {    
     
    Test.startTest();
    Batch_ShipmentDelete obj = new Batch_ShipmentDelete();
    DataBase.executeBatch(obj);            
    Test.stopTest();
 }
 //Database.Error[] errs = dr.getErrors();
 static testMethod void testMethod2()
 {           
    Test.startTest();
    Batch_ShipmentDelete obj = new Batch_ShipmentDelete();
    DataBase.executeBatch(obj);            
    Test.stopTest();
 }
    
}

Hi,
I have created one class to send the email to a particular customer When I call that class the send email method gives me success is true but email is not sending to the customer. Please check my code.

Please help me with this.
public class WorksContractEmailController{

public String strMessage{get;set;}

Public WorksContractEmailController(){
    try{
    String oppId = ApexPages.currentPage().getParameters().get('id'); 
    Opportunity oppObj = [Select Id,Account.PersonContactId,Works_Contract_Sign_Off_Date__c,Customer_Email__c From Opportunity Where Id = :oppId LIMIT 1];
    SendWorksContact(oppObj);
    }catch(Exception exp){
      strMessage = exp.getMessage();
    }
}


public PageReference SendWorksContact(Opportunity objOpp){
    try{
        if(objOpp.Works_Contract_Sign_Off_Date__c != null){
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            EmailTemplate templateId = [Select Id from EmailTemplate where name = 'Works_Contract_Attached' Limit 1];
            email.setTemplateID(templateId.Id);
            PageReference pdf = Page.WorksContractVFPage;
            pdf.getParameters().put('id',objOpp.id);
            pdf.setRedirect(true);
            Blob b = pdf.getContent();
            Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
            efa.setFileName('WorksContarct.pdf');
            efa.setBody(b);
            email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
            email.setToAddresses(new String[] {objOpp.Customer_Email__c});
            email.setTargetObjectId(objOpp.Account.PersonContactId);
            email.setSaveAsActivity(false);
            email.setWhatId(objOpp.Id);
            system.debug('------email----'+email);
            system.debug('------objOpp.Account.PersonContactId----'+objOpp.Account.PersonContactId);
            Messaging.SendEmailResult [] objResult = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email},false);
            if(objResult[0].isSuccess())
              strMessage = 'Email has been send.';
            else
             strMessage = 'Error - '+objResult[0].errors[0].message+' to send to the works contract,Please contact to your system administrator.';  
            system.debug('-----(objResult[0].isSuccess()----'+objResult[0].isSuccess());  
        }else{
            strMessage = 'Please update Works Contract sign off date.';
        }
    }catch(Exception exp){
      strMessage = exp.getMessage();
    }

 return null;

}


Thanks,