0

I am working on finishing up my Test Class to cover a new Batch Apex trigger I am writing however when I try to run the test I get the error: System.LimitException: Apex CPU time limit exceeded

I tried using System.debug(Limit.getCPULimit()); before and after the for loop where the system is saying the error is occurring however I get the error that the variable does not exist: Limit - when using that line.

Any help is appreciated as I feel I am so close to finishing this test class to get my coverage and be able to deploy the trigger.

Test Class Code below and the line the CPU limit is triggering on is the for(Lead l :leads){ line.

@isTest
private class LeadDailyUpdaterTest {
    @testSetup 
static void setup() {
    List<Lead> leads = new List<Lead>();
  
    // insert 200 Leads
    for (Integer i=0;i<200;i++) {
        leads.add(new lead(LastName='Lead BATCH TEST', FirstName='First '+i, Company='Lead' +i, Status='Open'));
    }

    // insert leads first
    insert leads;

    Datetime setDate = Datetime.now().addDays(-31);
    // then you can call setCreatedDate (needs to be done on each individual record)
    for(Lead l :leads){
        test.setCreatedDate(l.Id, setDate);
    }
}
    static testmethod void test() {
        Test.startTest();
        LeadDailyUpdater uca = new LeadDailyUpdater();
        Id batchId = Database.executeBatch(uca);
        Test.stopTest();
        // after the testing stops, assert records were updated properly
        System.assertEquals(200, [select count() from lead where leadsource = 'Closed - No Response' and LastName ='Lead BATCH TEST']);
    }
}

There are no other Triggers that I have created on the Lead Object, there is only a Trigger from Marketo present so I do not believe it is due to other triggers, Below is my Trigger that I have where I am simply looking to pull all leads with Last Modified greater than 30 days ago then update the Status:

global class LeadDailyUpdater implements Database.Batchable<sObject>{
    
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator ([select id, LastModifiedDate, Status, leadSource from Lead Where LastModifiedDate < LAST_N_DAYS:30]);
    }
    
    global void execute(Database.BatchableContext bc,List<lead> scope)
    {
        List<Lead> leads=new List<Lead>();
        for(lead l : scope)
        {
            l.LeadSource='Closed - No Response';
            leads.add(l);
        }
        update leads;
    }
    
    global void finish(Database.BatchableContext bc)
    {
      AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id = :bc.getJobId()];
        system.debug(job);
    }     
}

Again I appreciate any insight or guidance as this has me truly stumped.

1
  • You should be using an IDE. As it would have suggested its not Limit its Limits, so Limits.getCpuTime() Dec 23, 2020 at 0:59

1 Answer 1

2

You should be using an IDE. As it would have suggested its not Limit its Limits, so Limits.getCpuTime(), also I the just ran the code for testSetup, and it hardly took 400 ms to run. So i believe your org might be having either PB, or WF or Triggers on Leads. Its better to use a Log Analysis window to debug which process is taking time.

  1. Generate your logs in finest level.

  2. Then navigate to your developer console window.

  3. Select analysis as from dropdown.

enter image description here

  1. Now navigate to timeline window as shown below and check which process is taking time. You can even check Limits tab here.

enter image description here

5
  • Thanks for this guide, I never knew about this function and its great!! I do see that it shows Workflow with 17,340 Millis on the timeline accounting for 79% of the run so that seems to be the cause since DB and Apex are only a few % points. -- How can I reduce that down? we have workflows for assigning certain fields based on specific values when leads are created so we need that function, is there a way to not run them with this Batch trigger/Test Class? since I only need it to focus on the Status. Dec 23, 2020 at 23:52
  • Also if you have a recommendation for IDE I would love to hear it since I just been using the Dev Console. Dec 23, 2020 at 23:53
  • Workflows and other system processes dont run in bulk, this would need thorough debugging and development as to why workflow are taking time and if few of them can be moved to triggers and reduce the execution time. Dec 24, 2020 at 1:13
  • For IDE this is not a platform to favor one, i recommend googling it. Dec 24, 2020 at 1:13
  • I noticed that a lot of it comes from the 200 records I am trying to test... is it possible to edit the trigger/test class to set a smaller batch size? this will run at night and as such no impact so if it did say 50 at a time instead of the default 200 I wonder if that will keep it from the limiter. Where/how would I set the batch size? Dec 24, 2020 at 20:35

You must log in to answer this question.

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