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
Thanigai Kumaran BalajiThanigai Kumaran Balaji 

I am stuck with test class for below batch apex that use input from flow

My Batch apex:

public class exportobascsv implements Database.Batchable <SObject>, Database.Stateful {
        public Final String Feildnamefromuser;
        public Final Boolean fullbackup;
        public Final Boolean partialbackup;
           public Final String Objectname;    
        public Final String Email;
        public Final Boolean Backupbetweenintervals;
        public Final Datetime Backupstartingfrom;
        public Final Datetime BackupEnddatetime;
    public exportobascsv(Boolean full,String Feildname,Boolean partial,String obj, String Emailid, Boolean intervals, Datetime start, Datetime endtime)
    {
        fullbackup = full;
        Feildnamefromuser = Feildname;
        partialbackup = partial;
        Objectname = obj;
        Email = Emailid;
        Backupbetweenintervals = intervals;
        Backupstartingfrom = start;
        BackupEnddatetime = endtime;
    }
        
   public Database.QueryLocator start (Database.BatchableContext bc)
{
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Map<String, Schema.SObjectField> fieldMap = schemaMap.get(Objectname).getDescribe().fields.getMap();
// query to return Object 
String query = 'Select ';       
for(String fieldName : fieldMap.keyset() )
    {
        query += fieldname+',';   
        }
query = query.removeEnd(',');
    if(Backupbetweenintervals == true)
    {
         String newbackupfrom = Backupstartingfrom.format('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'');
        String newbackuptill = BackupEnddatetime.format('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'');   
     if(!test.isRunningTest()){
        query += ' from ' +Objectname+ ' where lastmodifieddate >= ' +newbackupfrom+ ' and lastmodifieddate <= ' +newbackuptill+ '';
     }else{
            query += ' from ' +Objectname+ '';
     }  }
    else {
        if(!test.isRunningTest()){
        query += ' from ' +Objectname+ ' where lastmodifieddate = yesterday';
     }else{
            query += ' from ' +Objectname+ '';
     } 
    }
         return Database.getQueryLocator(query);
}
   public void execute(Database.BatchableContext bc, List<sobject> OppList)
   {   
 try{      
  
    String generatedCSVFile = '';
        if(fullbackup == true)
    {
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Map<String, Schema.SObjectField> fieldMap = schemaMap.get(Objectname).getDescribe().fields.getMap();
        for(String fieldName : fieldMap.keyset() )
    {
        generatedCSVFile += Fieldname +',';     
        }
generatedCSVFile = generatedCSVFile.removeEnd(',');
generatedCSVFile = generatedCSVFile + '\n'; 
for(sObject company: OppList){
  for(String fieldName : fieldMap.keyset() )
    {
        generatedCSVFile += company.get(fieldName)+ ',';     
        }
        generatedCSVFile = generatedCSVFile.removeEnd(',');
        generatedCSVFile = generatedCSVFile + '\n'; 

    }else if(partialbackup == true )
    {
        
//Split the text in Feild name as separate lines
list<String> eachline = Feildnamefromuser.split(' ');
for(Integer i = 0; i < eachline.size(); i++)
{
        generatedCSVFile += eachline[i] +',';            
}
generatedCSVFile = generatedCSVFile.removeEnd(',');
generatedCSVFile = generatedCSVFile + '\n'; 
for(sobject company: OppList){
 for(Integer i = 0; i < eachline.size(); i++)
{
        generatedCSVFile += company.get(eachline[i])+ ',';     
        }
    generatedCSVFile = generatedCSVFile.removeEnd(',');
    generatedCSVFile = generatedCSVFile + '\n'; 

    }

//send email with generated csv file
String Email1= Email;
Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
Blob csvBlob = blob.valueOf(generatedCSVFile);
String csvName = '' +Objectname+ ' backup.csv';
csvAttachment.setFileName(csvName);
csvAttachment.setBody(csvBlob);
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[]{Email1};
String subject = '' +Objectname+ '  backup';
email.setSubject(subject);
email.setToAddresses(toAddresses);
email.setPlainTextBody('Please find the Object backup file attached to the mail');
email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttachment});
Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
 
       }
       catch(exception e)
       {
            system.debug('Exception Caught:'+e.getmessage());
       }
       }
       
    public void finish(Database.BatchableContext bc)
    {
    }  
   

}


My Helper Apex class:

public class ExportObjectHelperclass {

        public static String Feildnamefromuser;
        public static Boolean fullbackup;
        public static Boolean partialbackup;
           public Static String Objectname;    
        public Static String Email;
        public Static Boolean Backupbetweenintervals;
        public Static Datetime Backupstartingfrom;
        public Static Datetime BackupEnddatetime;
  
 @InvocableMethod (Label ='call batch apex')
    public static void callbatch(List<FlowInputs> request) {
             
        fullbackup = request[0].Full_Object_Backup;
           Feildnamefromuser = request[0].Enter_Feild_API_name_with_inbetween;
        partialbackup = request[0].Partial;
          Objectname = request[0].Objectname;
        Email = request[0].Email;
        Backupbetweenintervals = request[0].Backupbetweenintervals;
        Backupstartingfrom = request[0].Backupstartingfrom;
        BackupEnddatetime = request[0].BackupEnddatetime;
        Id batchInstanceId = Database.executeBatch(new exportobascsv(fullbackup, Feildnamefromuser, partialbackup,Objectname,Email,Backupbetweenintervals,Backupstartingfrom,BackupEnddatetime));
        //exportobascsv objbatch = new exportobascsv();
         //Database.executeBatch(objbatch, 200);
    
      
    }
    
    public class FlowInputs{
    
        @InvocableVariable
        public Boolean Full_Object_Backup;
        @InvocableVariable
        public Boolean Partial;
        @InvocableVariable
        public String Enter_Feild_API_name_with_inbetween;
         @InvocableVariable
        public String Objectname;    
         @InvocableVariable
        public String Email;
         @InvocableVariable
        public Boolean Backupbetweenintervals;
        @InvocableVariable
        public Datetime Backupstartingfrom;
        @InvocableVariable
        public Datetime BackupEnddatetime;
    }  
}

My Test class which my helper class has 100% and batch class has 16%


    @isTest
    public Static Void unitTest1(){
        Account Acc = New Account();
        Acc.Name = 'Test Account';
        acc.Region__c = 'EMEA';
        Insert Acc;
        Opportunity Opp = new Opportunity();
        Opp.Name = 'Test Opportunity';
        Opp.AccountId = Acc.Id;
        Opp.CloseDate =System.today();
        Opp.StageName = 'Closed Won';
        
        Insert Opp;
        Export_Object_as_CSV__c csv= new Export_Object_as_CSV__c();
        //csv.name='sample';
        csv.Field_backup__c=true;
        csv.Field_name_Separated_with__c='Name';
         csv.Backup_between_interval__c = true;
        csv.Backup_from__c = System.today();
         csv.Backup_till__c = System.today() + 5;
        csv.Name = 'Account';
        csv.Email_ID__c = 'thanigai.k.balaji@apisero.com';
        insert csv;
        ExportObjectHelperclass.FlowInputs fi = new ExportObjectHelperclass.FlowInputs();
        fi.Enter_Feild_API_name_with_inbetween = 'name';
        fi.Full_Object_Backup = true;
        fi.Partial = false;
        
        test.startTest();    
        
        ExportObjectHelperclass.callbatch(new List<ExportObjectHelperclass.FlowInputs>{fi});
        exportobascsv cs=new exportobascsv(true, 'name', false, 'Account', 'thanigai.k.balaji@apisero.com', false, System.today(), System.today()+5);
        Id batchId = Database.executeBatch(cs);
             
        test.stopTest();
        
    }
}
Best Answer chosen by Thanigai Kumaran Balaji
Thanigai Kumaran BalajiThanigai Kumaran Balaji
no longer needed