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
LakshmanLakshman 

Need help to write Test Class

Hi Friends,


I have created a Schedulable job.
Apex Class is :

global class scheduledUpdateOnOppurtunity implements Database.Batchable<SObject>, Database.AllowsCallouts{
public String query ;
public Date currentDate =  date.today();
public Integer monthDays =  date.daysInMonth(currentDate.year(), currentDate.month())-1;
public Date startOfMonth = currentDate.toStartOfMonth();
public Date endOfMonth = startOfMonth.addDays(monthDays);         
public Integer currentFinancialYear = currentDate.year();
public date currentQuarterStart;
public date currentQuarterEnd;
public date firstQuarterStart;
public date firstQuarterEnd;
public date secondQuarterStart;
public date secondQuarterEnd;
public date thirdQuarterStart;
public date thirdQuarterEnd;
public date forthQuarterStart;
public date forthQuarterEnd;

global database.Querylocator start(Database.BatchableContext BC){
       query = 'SELECT CloseDate, Closed_date_Today__c,Closed_date_StartOfMonth__c, Closed_date_EndOfMonth__c, Closed_date_CurrentQuarterStart__c, Closed_date_CurrentQuarter__c from Opportunity WHERE isClosed = false';
       return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC,Sobject[] scope)
{
          if(currentDate.month() <=3 ){
              currentFinancialYear = currentDate.year() - 1;
          }
          firstQuarterStart = date.newInstance(currentFinancialYear, 04, 01);
          firstQuarterEnd = date.newInstance(currentFinancialYear, 06, 30);
          secondQuarterStart = date.newInstance(currentFinancialYear, 07, 01);
          secondQuarterEnd = date.newInstance(currentFinancialYear, 09, 30);          
          thirdQuarterStart = date.newInstance(currentFinancialYear, 10, 01);
          thirdQuarterEnd = date.newInstance(currentFinancialYear, 12, 31);          
          forthQuarterStart = date.newInstance(currentFinancialYear+1, 01, 01);
          forthQuarterEnd = date.newInstance(currentFinancialYear+1, 03, 31);              
          if (currentDate >= firstQuarterStart && currentDate <= firstQuarterEnd ){
              currentQuarterStart = firstQuarterStart;
              currentQuarterEnd = firstQuarterEnd;
          }
          if (currentDate >= secondQuarterStart && currentDate <= secondQuarterEnd ){
              currentQuarterStart = secondQuarterStart;
              currentQuarterEnd = secondQuarterEnd;
          }
          if (currentDate >= thirdQuarterStart && currentDate <= thirdQuarterEnd ){
              currentQuarterStart = thirdQuarterStart;
              currentQuarterEnd = thirdQuarterEnd;
          }
          if (currentDate >= forthQuarterStart && currentDate <= forthQuarterEnd ){
              currentQuarterStart = forthQuarterStart;
              currentQuarterEnd = forthQuarterEnd;
          }         
            
           try{
                List<Opportunity> listOppUpdate = new List<Opportunity>();
                           
                 for(sobject s : scope){
                      Opportunity opp = (Opportunity)s;
                if (opp.CloseDate > currentDate){
                    opp.Closed_date_Today__c = true;
                }else{        
                    opp.Closed_date_Today__c = false;
                }
                if (opp.CloseDate >= startOfMonth){
                    opp.Closed_date_StartOfMonth__c = true;
                }else{
                    opp.Closed_date_StartOfMonth__c = false;
                }
                if (opp.CloseDate <= endOfMonth){
                    opp.Closed_date_EndOfMonth__c = true;
                }else{
                    opp.Closed_date_EndOfMonth__c = false;
                }
                if(opp.CloseDate >= currentQuarterStart){
                    opp.Closed_date_CurrentQuarterStart__c = true;
                }else{
                    opp.Closed_date_CurrentQuarterStart__c = false;
                }         
                if(opp.CloseDate <= currentQuarterEnd){
                    opp.Closed_date_CurrentQuarter__c = true;
                }else{
                    opp.Closed_date_CurrentQuarter__c = false;
                }     
                    
                   listOppUpdate.add(opp);
                    
                   if(listOppUpdate.size() > 999){
                       database.update(listOppUpdate,false);
                        listOppUpdate = new List<Opportunity>();
                   }
                 }
                 
                 if(listOppUpdate.size() > 0){
                     database.update(listOppUpdate,false);
                 }
                 
              }
              catch(Exception ex){
                  system.debug(ex.getMessage());
              }  
      
  }
  global void finish(Database.BatchableContext BC){
  }
}

Code coverage is 32% only. How I can improve this coverage?

I'm adding Test Class in my second message.

LakshmanLakshman

Test Class is as follows :


@isTest
private class TestSchedulableUpdateOpportunity {  
      
    public static testmethod void DoTestSch(){
          Date currentDate =  date.today();
          Integer monthDays =  date.daysInMonth(currentDate.year(), currentDate.month())-1;
          Date startOfMonth = currentDate.toStartOfMonth();
          Date endOfMonth = startOfMonth.addDays(monthDays);         
          Integer currentFinancialYear = currentDate.year();
          
          if(currentDate.month() <=3 ){
              currentFinancialYear = currentDate.year() - 1;
          }        
          date firstQuarterStart = date.newInstance(currentFinancialYear, 04, 01);
          date firstQuarterEnd = date.newInstance(currentFinancialYear, 06, 30);
          
          date secondQuarterStart = date.newInstance(currentFinancialYear, 07, 01);
          date secondQuarterEnd = date.newInstance(currentFinancialYear, 09, 30);
          
          date thirdQuarterStart = date.newInstance(currentFinancialYear, 10, 01);
          date thirdQuarterEnd = date.newInstance(currentFinancialYear, 12, 31);
          
          date forthQuarterStart = date.newInstance(currentFinancialYear+1, 01, 01);
          date forthQuarterEnd = date.newInstance(currentFinancialYear+1, 03, 31);        
          
          date currentQuarterStart;
          date currentQuarterEnd;
          
          if (currentDate >= firstQuarterStart && currentDate <= firstQuarterEnd ){
              currentQuarterStart = firstQuarterStart;
              currentQuarterEnd = firstQuarterEnd;
          }
          if (currentDate >= secondQuarterStart && currentDate <= secondQuarterEnd ){
              currentQuarterStart = secondQuarterStart;
              currentQuarterEnd = secondQuarterEnd;
          }          
          if (currentDate >= thirdQuarterStart && currentDate <= thirdQuarterEnd ){
              currentQuarterStart = thirdQuarterStart;
              currentQuarterEnd = thirdQuarterEnd;
          }
          if (currentDate >= forthQuarterStart && currentDate <= forthQuarterEnd ){
              currentQuarterStart = forthQuarterStart;
              currentQuarterEnd = forthQuarterEnd;
          }
            
        List<Opportunity> lstOpp = new List<Opportunity>();
                     
        for(Opportunity opp : [Select CloseDate, Closed_date_Today__c,Closed_date_StartOfMonth__c, Closed_date_EndOfMonth__c, Closed_date_CurrentQuarterStart__c, Closed_date_CurrentQuarter__c From Opportunity WHERE isClosed = false LIMIT 100]){
                      
            if (opp.CloseDate > currentDate){
                opp.Closed_date_Today__c = true;
            }else{        
                opp.Closed_date_Today__c = false;
            }
            if (opp.CloseDate >= startOfMonth){
                opp.Closed_date_StartOfMonth__c = true;
            }else{
                opp.Closed_date_StartOfMonth__c = false;
            }
            if (opp.CloseDate <= endOfMonth){
                opp.Closed_date_EndOfMonth__c = true;
            }else{
                opp.Closed_date_EndOfMonth__c = false;
            }
            if(opp.CloseDate >= currentQuarterStart){
                opp.Closed_date_CurrentQuarterStart__c = true;
            }else{
                opp.Closed_date_CurrentQuarterStart__c = false;
            }         
            if(opp.CloseDate <= currentQuarterEnd){
                opp.Closed_date_CurrentQuarter__c = true;
            }else{
                opp.Closed_date_CurrentQuarter__c = false;
            }  
            lstOpp.add(opp);
        }
                                                      
        if(lstOpp.size() > 0){       
            database.update(lstOpp,false);    
        }
         
        Test.startTest();
        // call batch apex
        scheduledUpdateOnOppurtunity batchObj = new scheduledUpdateOnOppurtunity();
        ID batchprocessid = Database.executeBatch(batchObj);
        Test.stopTest();           
    }
}


Code coverage is 32% only. How I can improve this coverage?


LakshmanLakshman

The basic idea about this Shedulable job is to perform field updates (5 different checkboxes) on the basis of Opportunity close date.

hitzhitz

HI, Lakshman

 

I have created same senario like yours like created required fields in opportunity object , created class with Test class...

 

it covers 78% for..... :)

 

i think you have seen something wrong..... check it again......

 

or check ur class reflect with another class or trigger ..... please check it..

 

LakshmanLakshman

Yes I have another class

 

global class scheduleUpdateCheckIn implements Schedulable {

  global void execute(SchedulableContext context) {
    // call batch apex
    scheduledUpdateOnOppurtunity batchObj = new scheduledUpdateOnOppurtunity();
    ID batchprocessid = Database.executeBatch(batchObj);
  }
}

 

But test class for this have 100% coverage.

This class is just implementing Schedulable interface and invoking batch apex.

 

While running TestScheduleUpdateCheckIn test class, coverage for above class is zero. So it might be the reason.

 

How can I cover this? any idea?

TechiesTechies

for ur schedule class

 

 scheduleUpdateCheckIn objSchedule =new scheduleUpdateCheckIn ();       
        Test.startTest();
     String jobId = System.schedule('testBasicScheduledApex1','0 55 * * * ?', objSchedule);
        
        CronTrigger ct = [SELECT id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
        
        System.assertEquals(0, ct.TimesTriggered);
        Test.stopTest();

 

 

Regards,

Kiran

 

LakshmanLakshman

Thanks Kiran,

 

I already have TestClass for Schedulable and its coverage is 100%. But the other class which is implementing Database.Batchable is showing 30% coverage.

 

 

hitzhitz

HI ....

 

It is necessary to created Different Schedulable Class to run your Batch Class ........... ?

 

Why Dont you try to implement Schedulable in to your Batch Class and write your execute() method in your class ...... i.e...

 

global class scheduledUpdateOnOppurtunity implements Database.Batchable<SObject>, Database.AllowsCallouts, Schedulable {

 

// TODO Your Code..............

.................

..........................

.....................

 

 

 

  global void execute(SchedulableContext context) {
    // call batch apex
    scheduledUpdateOnOppurtunity batchObj = new scheduledUpdateOnOppurtunity();
    Database.executeBatch(batchObj);
  }

}

 

and in you test method just call you execute method

 

LakshmanLakshman

Hitesh,

 

Now I have modified class as follows :

 

global class scheduledUpdateOnOppurtunity implements Database.Batchable<SObject>, Database.AllowsCallouts, Schedulable{
 
public String query ;
public Date currentDate =  date.today();
public Integer monthDays =  date.daysInMonth(currentDate.year(), currentDate.month())-1;
public Date startOfMonth = currentDate.toStartOfMonth();
public Date endOfMonth = startOfMonth.addDays(monthDays);         
public Integer currentFinancialYear = currentDate.year();
public date currentQuarterStart;
public date currentQuarterEnd;
public date firstQuarterStart;
public date firstQuarterEnd;
public date secondQuarterStart;
public date secondQuarterEnd;
public date thirdQuarterStart;
public date thirdQuarterEnd;
public date forthQuarterStart;
public date forthQuarterEnd;

global database.Querylocator start(Database.BatchableContext BC){
       query = 'SELECT CloseDate, Closed_date_Today__c,Closed_date_StartOfMonth__c, Closed_date_EndOfMonth__c, Closed_date_CurrentQuarterStart__c, Closed_date_CurrentQuarter__c from Opportunity WHERE isClosed = false';
       return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC,Sobject[] scope)
{
          if(currentDate.month() <=3 ){
              currentFinancialYear = currentDate.year() - 1;
          }
          firstQuarterStart = date.newInstance(currentFinancialYear, 04, 01);
          firstQuarterEnd = date.newInstance(currentFinancialYear, 06, 30);
          
          secondQuarterStart = date.newInstance(currentFinancialYear, 07, 01);
          secondQuarterEnd = date.newInstance(currentFinancialYear, 09, 30);
          
          thirdQuarterStart = date.newInstance(currentFinancialYear, 10, 01);
          thirdQuarterEnd = date.newInstance(currentFinancialYear, 12, 31);
          
          forthQuarterStart = date.newInstance(currentFinancialYear+1, 01, 01);
          forthQuarterEnd = date.newInstance(currentFinancialYear+1, 03, 31);        
          
        
          if (currentDate >= firstQuarterStart && currentDate <= firstQuarterEnd ){
              currentQuarterStart = firstQuarterStart;
              currentQuarterEnd = firstQuarterEnd;
          }
          
          if (currentDate >= secondQuarterStart && currentDate <= secondQuarterEnd ){
              currentQuarterStart = secondQuarterStart;
              currentQuarterEnd = secondQuarterEnd;
          }
          
          if (currentDate >= thirdQuarterStart && currentDate <= thirdQuarterEnd ){
              currentQuarterStart = thirdQuarterStart;
              currentQuarterEnd = thirdQuarterEnd;
          }
          
          if (currentDate >= forthQuarterStart && currentDate <= forthQuarterEnd ){
              currentQuarterStart = forthQuarterStart;
              currentQuarterEnd = forthQuarterEnd;
          }         
            
           try{
                List<Opportunity> listOppUpdate = new List<Opportunity>();
                           
                 for(sobject s : scope){
                      Opportunity opp = (Opportunity)s;
                
                //if Close Date is less than Today then set Closed_date_Today__c to true else set it to false
                if (opp.CloseDate > currentDate){
                    opp.Closed_date_Today__c = true;
                }else{        
                    opp.Closed_date_Today__c = false;
                }
        
                //if Close Date is greater than equal to start of month then set Closed_date_StartOfMonth__c to true else set it to false
                if (opp.CloseDate >= startOfMonth){
                    opp.Closed_date_StartOfMonth__c = true;
                }else{
                    opp.Closed_date_StartOfMonth__c = false;
                }
        
                //if Close Date is in in the current month and is greater than Today then set Closed_date_EndOfMonth__c to true else set it to false
                if (opp.CloseDate <= endOfMonth){
                    opp.Closed_date_EndOfMonth__c = true;
                }else{
                    opp.Closed_date_EndOfMonth__c = false;
                }
        
                //if Close Date is greater than Start of Current quarter then set Closed_date_CurrentQuarterStart__c to true else set it to false
                if(opp.CloseDate >= currentQuarterStart){
                    opp.Closed_date_CurrentQuarterStart__c = true;
                }else{
                    opp.Closed_date_CurrentQuarterStart__c = false;
                }         
        
                //if Close Date lies in the current quarter then set Closed_date_CurrentQuarter__c to true else set it to false
                if(opp.CloseDate <= currentQuarterEnd){
                    opp.Closed_date_CurrentQuarter__c = true;
                }else{
                    opp.Closed_date_CurrentQuarter__c = false;
                }     
                    
                   listOppUpdate.add(opp);
                    
                   if(listOppUpdate.size() > 999){
                       database.update(listOppUpdate,false);
                        listOppUpdate = new List<Opportunity>();
                   }
                 }
                 
                 if(listOppUpdate.size() > 0){
                     database.update(listOppUpdate,false);
                 }
                 
              }
              catch(Exception ex){
                  system.debug(ex.getMessage());
              }  
      
  }
 
  global void finish(Database.BatchableContext BC){
  }

  global void execute(SchedulableContext context) {
    // call batch apex
    scheduledUpdateOnOppurtunity batchObj = new scheduledUpdateOnOppurtunity();
    Database.executeBatch(batchObj);
  }
 
}

 

And test method

@isTest
private class TestSchedulableUpdateOpportunity {  
      
    public static testmethod void DoTestSch(){
        
        Test.startTest();
        scheduledUpdateOnOppurtunity batchObj = new scheduledUpdateOnOppurtunity();
        SchedulableContext context;
        batchObj.execute(context);
        Test.stopTest();     
    }
}

 

But coverage is still 30% :(

hitzhitz

HI............

 

Use Below Code for your test

 

 

@isTest
private class TestSchedulableUpdateOpportunity {  
      
    public static testmethod void DoTestSch(){
          
         
        Test.startTest();
        // call batch apex
        scheduledUpdateOnOppurtunity batchObj = new scheduledUpdateOnOppurtunity();
        ID batchprocessid = Database.executeBatch(batchObj);
        Test.stopTest();           
    }
}

LakshmanLakshman

Hi,

I used the code in my test but still the coverage is 26% :(

 

LakshmanLakshman

Hitesh,

 

After running this testMethod, I can see following in log files.

 

 

08:01:17.399|EXCEPTION_THROWN|[EXTERNAL]|System.UnexpectedException: No more than one executeBatch can be called from within a testmethod. Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.
08:01:17.411|FATAL_ERROR|System.UnexpectedException: No more than one executeBatch can be called from within a testmethod. Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.

 


LakshmanLakshman

HI Hitesh,

 

 

Thanks for all your help and suggestions.

 

After adding limit of 200 in query, I'm able to have test coverage 80%.

 

Regards

Lakshman