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
Raju kanoperiRaju kanoperi 

Hi guys i have test class am getting only 54% code coverage can u guys help me on the test class Thanks

Apex class:
global class AhHandlingEmailservice implements Messaging.InboundEmailHandler {
    global Messaging.Inboundemailresult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
        List<DY_Proposal_Attachment__c> proposalList = new List<DY_Proposal_Attachment__c>();
        List<Attachment> attList = new List<Attachment>();
        List<Error_Log__c> errorlogList=new List<Error_Log__c>();
        Map<String,Blob> AttachmentBody = new Map<String,Blob>();
        Set<Integer> proposalIdSet = new Set<Integer>();
        List<Integer> ProposalidsList=new List<Integer>();
        Map<Integer,String> Messagemap= new Map<Integer,String>();
        List<Id> SuccessIdsList= new List<Id>();
           
        try
        {
            for(Messaging.Inboundemail.Binaryattachment bAttachment: email.binaryAttachments){
                string fileName=bAttachment.fileName;
                  if(fileName.lastindexOf('_')!=-1 && fileName.endswith('.pdf')) {
                    Integer propId= integer.valueof(fileName.substring(fileName.indexOf('_')+1,fileName.indexOf('.pdf')));
                      ProposalidsList.add(propId);
                 }
                                
                }
            
         List<DY_Proposal_Attachment__c> dyproposal= new List<DY_Proposal_Attachment__c>([Select id,name,ProposalPDFID__c From DY_Proposal_Attachment__c where ProposalPDFID__c IN:ProposalidsList]);
         
         for(DY_Proposal_Attachment__c dypa:dyproposal){
            Integer propId= integer.valueOf(dypa.ProposalPDFID__c);
              proposalIdSet.add(propId);
         }  
         for( Messaging.Inboundemail.Binaryattachment bAttachment: email.binaryAttachments){
                 string fileName=bAttachment.fileName;
                 Blob body=bAttachment.body;
                 String Message='';
                 Integer propId=integer.valueof(fileName.substring(fileName.indexof('_')+1,filename.indexof('.pdf')));
             if(fileName.lastindexOf('_')!=-1 && fileName.endswith('.pdf')) {  
                 String name = fileName.substring(0,fileName.indexOf('.pdf'));
             if(!proposalIdSet.contains(propId)){
                      DY_Proposal_Attachment__c dypa = new DY_Proposal_Attachment__c();
                      dypa.Name = name;
                      dypa.ProposalPDFID__c = propId;
                      AttachmentBody.put(dypa.Name,body);
                      proposalList.add(dypa);
                     }else{
                       Message='Duplicate Record can not Insert';
                       Messagemap.put(propId,Message);
                                   
                    }
                   
                   }else{
                        Message='File Name should be a proper format';
                        Messagemap.put(propId,Message);  
                   }
                   
                  }  
            
           if(proposalList.size()>0){
                insert proposalList;
               
            }
              
            if(proposalList.size()>0){
              
              for(DY_Proposal_Attachment__c proAtt:proposalList){
                     Attachment attachment = new Attachment();
                     attachment.ParentId = proAtt.Id;
                     attachment.Body = AttachmentBody.get(proAtt.name);
                     attachment.Name = proAtt.name +'.pdf';
                     attList.add(attachment);
              }
            }
            
            if(attList.size()>0){
                             
             Database.saveResult[] attRecs = Database.insert(attList,false);
             for(Database.SaveResult sr:attRecs){
             if (sr.isSuccess()) {
                 SuccessIdsList.add(sr.getId());
                
             }
            
              }
                   
                }
            
             if(SuccessIdsList.size() == email.binaryAttachments.size()){
                 result.message = 'Your record(s) Successfully Inserted';    
             }
             else{
                  String myCustomMsg = 'The following attachment(s) insertion got failed.';
                
                 for(Integer aProposalId : Messagemap.keySet()){
                     myCustomMsg += 'The Attachment with the ProposalId '+aProposalId+' insertion got failed due to '+Messagemap.get(aProposalId)+' \n';   
                 }
                 result.message = myCustomMsg;
             }  
            
         }catch(Exception e){
              result.success = False;
              System.debug('Exception: '+e.getMessage());
              result.message = 'Failed to insert an attachment. '+e.getMessage();
              createErrorRecord(e.getMessage());
         }
              return result;
                  
         }
      
      public static void createErrorRecord(string exceptionMessage){
              system.debug('---ErrorLog----');
             Error_Log__c newErrorRecord = new  Error_Log__c();
                 newErrorRecord.Your_comments__c = exceptionMessage;
                // newErrorRecord.Name = fileName.substring(0,fileName.indexOf('.pdf'));
                 newErrorRecord.Name =  'Email Services Error Insert';
                 newErrorRecord.Processed_date__c = system.now();
                 newErrorRecord.Status__c = 'New';
                 newErrorRecord.Source__c = 'CorSales-StopLoss';
                 newErrorRecord.Object__c = 'DY Proposal';
                 newErrorRecord.Error_Type__c = 'Email Services';
                 Database.insert(newErrorRecord,false);
   }
    
  }


Test class:

@isTest(SeeAllData=False)

 public class AhHandlingEmailserviceTest{
   private static testmethod void Emailattachmentinsert(){

// create DY proposal attachment record

    DY_Proposal_Attachment__c Dyatt= new DY_Proposal_Attachment__c();
         Dyatt.name='Sample_786';
         Dyatt.ProposalPDFID__c= 786;
         Dyatt.Proposal_attached_successfully__c=true;
         insert Dyatt;
 // DY_Proposal_Attachment__c dyp=[select id,name,ProposalPDFID__c From DY_Proposal_Attachment__c where ProposalPDFID__c=:Dyatt.Id];
     Messaging.InboundEmail email = new Messaging.InboundEmail();
     Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
   
        email.subject = 'Test Proposal';
        email.fromname = 'sudhakar';
        env.fromAddress = 'rcomext.com';
     Error_Log__c newErrorRecord = new  Error_Log__c();
                 newErrorRecord.Name = 'Email Services Error Insert';
                 newErrorRecord.Processed_date__c = system.now();
                 newErrorRecord.Status__c = 'New';
                 newErrorRecord.Source__c = 'CorSales-StopLoss';
                 newErrorRecord.Object__c = 'DY Proposal';
                 newErrorRecord.Error_Type__c = 'Email Services';
                 Database.insert(newErrorRecord,false);
      Messaging.Inboundemail.Binaryattachment attachment = new Messaging.Inboundemail.Binaryattachment();
                 attachment.Body = Blob.toPdf('Sample PDF Text');
                 attachment.fileName = 'Sample_786.pdf';
      
      email.binaryAttachments = new Messaging.Inboundemail.Binaryattachment[]{attachment};
      
          AhHandlingEmailservice emailHandler = new AhHandlingEmailservice();
      Test.startTest();
      Messaging.Inboundemailresult result = emailHandler.handleInboundEmail(email, env);
            system.assert(result.success,'InbountEmailResult returnd a Failure message');
      Test.stopTest();
}

}

 
Shashikant SharmaShashikant Sharma
Hi Raju,

Could you please share which lines of code not getting covered.

Thanks
Shashikant
Raju kanoperiRaju kanoperi
thanks fr u reply... where ever highlighted thick blue lines those lines not covered..

global class AhHandlingEmailservice implements Messaging.InboundEmailHandler {
    global Messaging.Inboundemailresult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
        List<DY_Proposal_Attachment__c> proposalList = new List<DY_Proposal_Attachment__c>();
        List<Attachment> attList = new List<Attachment>();
        List<Error_Log__c> errorlogList=new List<Error_Log__c>();
        Map<String,Blob> AttachmentBody = new Map<String,Blob>();
        Set<Integer> proposalIdSet = new Set<Integer>();
        List<Integer> ProposalidsList=new List<Integer>();
        Map<Integer,String> Messagemap= new Map<Integer,String>();
        List<Id> SuccessIdsList= new List<Id>();
           
        try
        {
            for(Messaging.Inboundemail.Binaryattachment bAttachment: email.binaryAttachments){
                string fileName=bAttachment.fileName;
                  if(fileName.lastindexOf('_')!=-1 && fileName.endswith('.pdf')) {
                    Integer propId= integer.valueof(fileName.substring(fileName.indexOf('_')+1,fileName.indexOf('.pdf')));
                      ProposalidsList.add(propId);
                 }
                                
                }
            
         List<DY_Proposal_Attachment__c> dyproposal= new List<DY_Proposal_Attachment__c>([Select id,name,ProposalPDFID__c From DY_Proposal_Attachment__c where ProposalPDFID__c IN:ProposalidsList]);
         
         for(DY_Proposal_Attachment__c dypa:dyproposal){
            Integer propId= integer.valueOf(dypa.ProposalPDFID__c);
              proposalIdSet.add(propId);
         }  
         for( Messaging.Inboundemail.Binaryattachment bAttachment: email.binaryAttachments){
                 string fileName=bAttachment.fileName;
                 Blob body=bAttachment.body;
                 String Message='';
                 Integer propId=integer.valueof(fileName.substring(fileName.indexof('_')+1,filename.indexof('.pdf')));
             if(fileName.lastindexOf('_')!=-1 && fileName.endswith('.pdf')) {  
                 String name = fileName.substring(0,fileName.indexOf('.pdf'));
             if(!proposalIdSet.contains(propId)){
                      DY_Proposal_Attachment__c dypa = new DY_Proposal_Attachment__c();
                      dypa.Name = name;
                      dypa.ProposalPDFID__c = propId;
                      AttachmentBody.put(dypa.Name,body);
                      proposalList.add(dypa);

                     }else{
                       Message='Duplicate Record can not Insert';
                       Messagemap.put(propId,Message);
                                   
                    }
                   
                   }else{
                        Message='File Name should be a proper format';
                        Messagemap.put(propId,Message);  

                   }
                   
                  }  
            
           if(proposalList.size()>0){
                insert proposalList;
               
            }
              
            if(proposalList.size()>0){
              
              for(DY_Proposal_Attachment__c proAtt:proposalList){
                     Attachment attachment = new Attachment();
                     attachment.ParentId = proAtt.Id;
                     attachment.Body = AttachmentBody.get(proAtt.name);
                     attachment.Name = proAtt.name +'.pdf';
                     attList.add(attachment);

              }
            }
            
            if(attList.size()>0){
                             
             Database.saveResult[] attRecs = Database.insert(attList,false);
             for(Database.SaveResult sr:attRecs){
             if (sr.isSuccess()) {
                 SuccessIdsList.add(sr.getId());

                
             }
            
              }
                   
                }
            
             if(SuccessIdsList.size() == email.binaryAttachments.size()){
                 result.message = 'Your record(s) Successfully Inserted';    
             }
             else{
                  String myCustomMsg = 'The following attachment(s) insertion got failed.';
                
                 for(Integer aProposalId : Messagemap.keySet()){
                     myCustomMsg += 'The Attachment with the ProposalId '+aProposalId+' insertion got failed due to '+Messagemap.get(aProposalId)+' \n';   
                 }
                 result.message = myCustomMsg;
             }  
            
         }catch(Exception e){
              result.success = False;

              System.debug('Exception: '+e.getMessage());
              result.message = 'Failed to insert an attachment. '+e.getMessage();
              createErrorRecord(e.getMessage());

         }
              return result;
                  
         }
      
      public static void createErrorRecord(string exceptionMessage){
              system.debug('---ErrorLog----');
             Error_Log__c newErrorRecord = new  Error_Log__c();
                 newErrorRecord.Your_comments__c = exceptionMessage;
                // newErrorRecord.Name = fileName.substring(0,fileName.indexOf('.pdf'));
                 newErrorRecord.Name =  'Email Services Error Insert';
                 newErrorRecord.Processed_date__c = system.now();
                 newErrorRecord.Status__c = 'New';
                 newErrorRecord.Source__c = 'CorSales-StopLoss';
                 newErrorRecord.Object__c = 'DY Proposal';
                 newErrorRecord.Error_Type__c = 'Email Services';
                 Database.insert(newErrorRecord,false);

   }
    
  }
Shashikant SharmaShashikant Sharma
Hi,

This looks a big class so i ca only give you idea to create sceanrios for exception and statisfying conditions to go in uncovered code. You have to create mutiple test methods for it.


1. fo coverage purpose createErrorRecord you could direcrly call like
 
try {
Integer i = 1/0;
}
catch( Exception e ) {
AhHandlingEmailservice.createErrorRecord(e);
}

Thanks