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
DaNae GrahamDaNae Graham 

Apex Error: List index out of bounds: 0

I keep getting the following error when I test the code below:
System.ListException: List index out of bounds: 0

This error occurs on lines 13, 34, 64, and 93.  It looks like the list is pulling no records and I cannot figure out why.  I have confirmed that all required fields are captured.  I referenced another article that said to use @isTest (seeAllData=true) and it is still not working.

Help would be greatly appreciated - thank you in advance!!



@isTest (seeAllData=true)
private class leadsTaskHandlerTest {

    @isTest static void testLeadsWorkflow() {

        Lead newLead = new Lead(
                        Company = 'Test Account', FirstName= 'Test', LastName= 'Lead',
                        LeadSource = 'Web', Country = 'Canada',  Email = 'something@gmail.com',
                        Status = 'Open', Lead_Type__c = 'New Car Franchise');
        insert newLead;

        Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhoId = :newLead.Id AND Subject = 'Evaluate and Assign Web Lead'];
        tasks[0].Status = 'Completed';
        update tasks[0];

        System.assert(taskCreatedForLead('Email Introduction of TradeRev to main contact person', newLead.Id));
        System.assert(taskCreatedForLead('Phone call to follow up from email of introduction', newLead.Id));
        System.assert(taskCreatedForLead('Schedule an appointment with lead; no voicemail if you don\'t connect', newLead.Id));
        System.assert(taskCreatedForLead('Attempt to contact lead to set appointment second time in the week', newLead.Id));
        System.assert(taskCreatedForLead('Any interest in TradeRev?; let\'s schedule a demo', newLead.Id));
        System.assert(taskCreatedForLead('Touch base to let them know about growth/updates of TradeRev', newLead.Id));
        System.assert(taskCreatedForLead('Are they ready to talk about TradeRev?', newLead.Id));

    }


  @isTest static void testContractWorkflow() {
        Lead newLead = new Lead(
                        Company = 'Test Account', FirstName= 'Test', LastName= 'Lead',
                        LeadSource = 'Web', Country = 'Canada',  
                        Status = 'Contract Given', Lead_Type__c = 'New Car Franchise');
        insert newLead;
        Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhoId = :newLead.Id AND Subject = 'Any questions on the Registration Forms?'];
        tasks[0].Status = 'Completed';
        update tasks[0];

        System.assert(taskCreatedForLead('Are the Registration Forms complete?', newLead.Id));
    }

    @isTest static void testDueDateEmail() {
        Lead newLead = new Lead(
                        Company = 'Test Account', FirstName= 'Test', LastName= 'Lead',
                        LeadSource = 'Web', Country = 'Canada', Email = 'something@gmail.com', 
                        Status = 'Contract Given', Lead_Type__c = 'New Car Franchise');
        insert newLead;
        Task newTask = new Task(    Priority = 'Normal', 
                                        Status = 'Not Started',
                                        ActivityDate = Date.today(), 
                                        WhoId = newLead.Id); 
        insert newTask;
        update newTask;
    }


    @isTest static void testFranchiseDealerWorkflow() {

        Account newAccount = new Account(
                        Name = 'Test Franchise Dealer',
                        AccountSource = 'Web',
                        Account_Type__c = 'New Car Franchise');
        insert newAccount;

        Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhatId = :newAccount.Id AND Subject = 'Set appointment for Installation and Training Franchise'];
        tasks[0].Status = 'Completed';
        update tasks[0];


        System.assert(taskCreatedForAccount('Assist with On-boarding', newAccount.Id));
        System.assert(taskCreatedForAccount('Launch Cars; Walk back lot and try identify more cars they can load', newAccount.Id));        
        System.assert(taskCreatedForAccount('Has buyer been in touch to make arrangements for payment/pickup?', newAccount.Id));
        System.assert(taskCreatedForAccount('Has buyer taken car? Mark car delivered', newAccount.Id));
        System.assert(taskCreatedForAccount('Use TradeRev for the Live Appraisals', newAccount.Id));    
        System.assert(taskCreatedForAccount('Any other cars to launch?', newAccount.Id));
        System.assert(taskCreatedForAccount('Reminder to buy cars on TradeRev', newAccount.Id));

        System.assert(taskCreatedForAccount('Feedback on TradeRev; any referrals?', newAccount.Id));
        System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Good time to sell cars on TradeRev', newAccount.Id));
        //System.assert(taskCreatedForAccount('Monthly Report; Tips For Better Listings', newAccount.Id));
        //System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Good time to sell cars on TradeRev', newAccount.Id));
        //System.assert(taskCreatedForAccount('Monthly Report; Tips For Better Listings', newAccount.Id));

    }

    @isTest static void testIndepedentDealerWorkflow() {

        Account newAccount = new Account(
                        Name = 'Test Independent Dealer',
                        AccountSource = 'Web',
                        Account_Type__c = 'Independent Dealer');
        insert newAccount;

        Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhatId = :newAccount.Id AND Subject = 'Set appointment for Installation and Training'];
        tasks[0].Status = 'Completed';
        update tasks[0];


        System.assert(taskCreatedForAccount('Assist with On-boarding', newAccount.Id));
        System.assert(taskCreatedForAccount('Any questions on bidding?', newAccount.Id));        
        System.assert(taskCreatedForAccount('Have they been bidding? Any cars in pending?', newAccount.Id));
        System.assert(taskCreatedForAccount('Won any cars? Discuss timing expectations for payment and pickup', newAccount.Id));
        System.assert(taskCreatedForAccount('If a car has been won; have they paid and picked up car yet?', newAccount.Id));    
        System.assert(taskCreatedForAccount('Feedback on TradeRev; any referrals?', newAccount.Id));
        System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Having success moving the cars bought on TradeRev?', newAccount.Id));
        System.assert(taskCreatedForAccount('Touch Point; How are you doing? Can I help with anything? Having success moving the cars bought on TradeRev?', newAccount.Id));

    }



    static boolean taskCreatedForLead(String subject, Id id) {
        Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhoId = :id AND Subject = :subject];
        if (tasks.size() > 0) {
            tasks[0].Status = 'Completed';
            update tasks[0];
            return true;
        }
        else {
            return false;
        }
    }

    static boolean taskCreatedForAccount(String subject, Id id) {
        Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhatId = :id AND Subject = :subject];
        if (tasks.size() > 0) {
            tasks[0].Status = 'Completed';
            update tasks[0];
            return true;
        }
        else {
            return false;
        }
    }
    
    
}
Best Answer chosen by DaNae Graham
Shashikant SharmaShashikant Sharma
Hi DaNae,


Ok Try one more thing 

Remove the condition WhoId = :newLead.Id in your test class like 

Task[] tasks = [SELECT Id, Subject FROM Task WHERE Subject = 'Evaluate and Assign Web Lead'];
        tasks[0].Status = 'Completed';

I think this will resolve the issue.

Thanks
Shashikant
 

All Answers

LBKLBK
Hi,

In the following code, you are trying to fetch a task record for a Lead that you just created.
 
Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhoId = :newLead.Id AND Subject = 'Evaluate and Assign Web Lead'];
        tasks[0].Status = 'Completed';
        update tasks[0];
Unless you have a Process, Workflow or a Trigger that creates Task as soon as a Lead is created, tasks list will be empty.

To avoid this error, put a condition check in place
For example,
Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhoId = :newLead.Id AND Subject = 'Evaluate and Assign Web Lead'];
if(tasks.size() > 0){
        tasks[0].Status = 'Completed';
        update tasks[0];
}
Use similar check in every place where you are getting this error.

Let me know if this helps.
 
DaNae GrahamDaNae Graham
Hi @LBK I tried your suggestion and it is still not working.  I have been debugging and it is clear that tasks are not being created even though the criteria (from the workflow) is being met - the workflow that creates the task once the lead is created.  Does anyone know what would cause workflows to not fire in a test class?
Shashikant SharmaShashikant Sharma
Hi,

Your query on Task not returing any result and then you are accessing item from 0t index and that is what causing the issue.

Task[] tasks = [SELECT Id, Subject FROM Task WHERE WhoId = :newLead.Id AND Subject = 'Evaluate and Assign Web Lead'];
 tasks[0].Status = 'Completed';

Resolution: I think you are expecting Task to be created by other process so make sure that condition to invoke that Trigger/Process Builder is matched so your query return result.


Thanks
Shashikant


 
DaNae GrahamDaNae Graham
Hi @[Shashikant Sharma],

You are correct, the task should be created per a workflow rule.  The criteria is being met in the lead being created in the class (I even double checked the spelling) and it is still not firing the workflow.  Is there another way to test or check this?  Perhaps some other functionality that doesn't fire workflow rules in a test class?
Shashikant SharmaShashikant Sharma
Hi,

I would suggest 

1. Check if Workflow is Active
2. If Workflow is Active then test use case manually if it creates the Task and WhatId is populated with the Account Record and Subject is Set Properly as per test class.

I think above check will debug the issue for you. If not then please post the Workflow Rule Screen Shot and Task Action Screen shot.

Thanks
Shashikant
DaNae GrahamDaNae Graham
@[Shashikant Sharma] I did try creating the lead with the same values in the test class and it does create the task.  Here are the screenshots you requested:

User-added image


User-added image

Thank you!
DaNae
Shashikant SharmaShashikant Sharma
Hi DaNae,


Ok Try one more thing 

Remove the condition WhoId = :newLead.Id in your test class like 

Task[] tasks = [SELECT Id, Subject FROM Task WHERE Subject = 'Evaluate and Assign Web Lead'];
        tasks[0].Status = 'Completed';

I think this will resolve the issue.

Thanks
Shashikant
 
This was selected as the best answer
DaNae GrahamDaNae Graham
Hi @[Shashikant Sharma] I tried that and it still did not work.  Any other thoughts?  I am really at a loss with this...
DaNae GrahamDaNae Graham
Does anyone else know any tips or strategies for this?  I have reached out to SF Support too and have not heard back
DaNae GrahamDaNae Graham
FInally found the problem - country should have been "CA" instead of "Canada" due to what is available in the picklist.