1

Need help in increasing the code coverage for the batch class. I have 5 such similar Batch classes where I have t increase CODE COVERAGE. They are all working fine in production, but due to code coverage issue I have to work on test cases, This where I am really struggling. As i am new to wirte test cases.

can any1 help regarding this...

Thanks in advance...

All these batch classes send emails to users and managers and other business ppl ,

global class batchclass implements Database.batchable<sobject>, schedulable{

public string q='select id, name from Opportunity'; //Added different where conditions to filter the data 

    global Database.QueryLocator start(Database.BatchableContext BC)    
        {
           if(Test.isRunningTest()){
            Query = Query + ' limit 1';
            }
          system.debug(Query);
         return Database.getQueryLocator(Query);   
        }
    global void execute(Database.BatchableContext BC, list<Opportunity> scope)     
        {      
          //system.Debug('hi');      

         try
           {
               Map<Id, Opportunity> mapop = new  Map<Id, Opportunity>(); 
               for(Opportunity op:scope){
                   if(!mapop.containsKey(op.Id) ){
                         mapop.put(op.Id, op);
                         system.debug(mapop);
                     }

               }
               List<Messaging.SingleEmailMessage> emails=new List<Messaging.SingleEmailMessage>(); 

     for(Id key:mapop.keyset()){
        //from this method i am sending emails to the USERS and their managers.....
        Messaging.SingleEmailMessage email= new Messaging.SingleEmailMessage(); 
        string[] toaddress= new String[]{'[email protected]'};
        string[] toaddress= new String[]{'[email protected]'};
        email.setToAddresses(toaddress);
        system.debug(email);
        email.setCcAddresses(toccaddress);
        system.debug(email);
       email.setSubject(‘Hello User’);
       email.setReplyTo(‘[email protected]’);
      email.setHTMLBody(HTMLBODy(mapop.get(key)));
      emails.add(email);

    system.debug(emails);   }

    Messaging.sendEmail(emails);
    }
    catch(Exception ex)
    {
    System.Debug(‘—–Exception—-‘+ex.getMessage());
     }
     }
     global void finish(Database.BatchableContext BC){
     //EMPTY METHOD…..
    }

    global void execute(SchedulableContext sc) {
     //We now call the batch class to be scheduled
     BatchL0_2MNEMAIL my = new BatchL0_2MNEMAIL();

     //Parameters of ExecuteBatch(context,BatchSize)
     Database.executeBatch(my, 1);
    }

     private string htmlbody(){

    // Code for the building an HTML BODY for the email called from EXECUTE METHOD of Batch apex.
    }
     }
     @isTest(SeeAllData = true)
     public class BatchTEST{      
       public static testMethod void BatchTEST1(){
         test.startTest();
          try{             
            batchclass BatchObj1 = new batchclass();
            BatchObj1.Query+= '';
            ID batch_processId=Database.batchclass(BatchObj1, 2);  
            batchclass m = new batchclass ();
            String sch = '20 30 8 10 2 ?';
            String jobID = system.schedule('Alert to USer', sch, m);       
        }catch(Exception ex){}
        test.stopTest();
    }`

1 Answer 1

1

First, Unless I am missing it, not sure how this compiles as I do not see a variable named Query in your class.

Second the google doc on implementing scheduable class has an entire test class written to show you what you need:

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_scheduler.htm

Keeping your test methods separately according to actual scenario and not one method for the entire class is a good pratice

Ignoring syntax and errors, the main reason your code coverage is low is that you never actually:

Execute the batch: database.executeBatch(BatchObj1);

Below is an example of a class structure and the test class

Apex Class:

public class batch_ACH_Verification_Refund implements Database.Batchable<ID>, Database.AllowsCallouts, Schedulable {

    public ID[] rec_ids_to_process;

    public static String CRON_EXP = '0 0 0 3 9 ? 2022';

    public void execute(SchedulableContext sc) {

        String query =.........


        batch_ACH_Verification_Refund b = new batch_ACH_Verification_Refund(orders.keySet());
        database.executebatch(b,10);
    }

    public batch_ACH_Verification_Refund(Set<ID> rec_ids){
        rec_ids_to_process = New ID[]{};
        rec_ids_to_process.addAll(rec_ids);
    }

    public batch_ACH_Verification_Refund(ID[] rec_ids){
        rec_ids_to_process = rec_ids;
    }

    public Iterable<ID> start(Database.BatchableContext BC) {
        return rec_ids_to_process;
    }

    public void execute(Database.BatchableContext info, ID[] ids) {

         ..some code.......

    }

    public void finish(Database.BatchableContext info) {}
}

And the main part of the test code:

Scheduler

private static testmethod void batch_Refund_Schedule_Test() { Test.startTest();

    // Schedule the test job 
    String jobId = System.schedule('testBasicScheduledApex',
    batch_ACH_Verification_Refund.CRON_EXP, 
    new batch_ACH_Verification_Refund(new ID[]{}));
    // Get the information from the CronTrigger API object 
    CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, 
    NextFireTime
    FROM CronTrigger WHERE id = :jobId];

    // Verify the expressions are the same 

    System.assertEquals(batch_ACH_Verification_Refund.CRON_EXP, 
    ct.CronExpression);

    // Verify the job has not run 

    System.assertEquals(0, ct.TimesTriggered);

    // Verify the next time the job will run 

    System.assertEquals('2022-09-03 00:00:00', 
    String.valueOf(ct.NextFireTime));


Test.stopTest();

}

Batch -- Keep in mind to create the records you require for testing to meet the logic of the actual code in the batch. Using SEEALLDATA=TRUE is BAD Practice

@isTest
private class test_batch{

   private static test method void runTest(){

        ...create required records here....
      test.startTest();
          batch_ACH_Verification_Refund b = New batch_ACH_Verification_Refund(New ID[]{some ids});
         database.execute(b);
      test.stoptest();

      ..query for records and assert that the proper value exist after the process ran (If applicable)...

   }

}
1
  • thanks for the reply. I typed some of them and some i copy and pasted. So there are some mistakes. as you said they QUERY is not initialised its the string defined using 'q'variable. and its DATABASE.EXECUTEBATCH() in test method..... But i made mistakes here..... LET ME TRY THIS.. and see whether i can sort this out and increase my code coverage...
    – Yahuuu
    Dec 12, 2014 at 14:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .