Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Salesforce
  3. Question
Salesforce

What must be done when a list has no rows for assignment to

Asked by Aashish Chaursiya Apr 17, 2023 5.7K views 2 answers
Share

About this question

I'm having an issue with my Apex Test Class from a trigger. I've used the trigger multiple times in my sandbox but when I try to test it out it fails. The reason for the failure is 'System.QueryException: List has no rows for assignment to SObject' which I have tried to look up but there are so many answers and they don't apply to my case. Tried it multiple ways and I am wondering if anybody here has a good answer.


I have two objects, Implementation (custom) and Opportunity. The trigger fires when an Opportunity is set to 'Closed Won'. Below is the trigger:


    trigger CreateImplementation on Opportunity (after update) {
    List opps = new List();
    for ( Opportunity opp : Trigger.new ){


        if((opp.StageName == 'Closed Won' ) &&
        (Trigger.oldMap.get(opp.Id).StageName!='Closed Won') ) {
        opps.add(opp.Id);
    }
    Map oppsMap = new Map( [SELECT Id, Account.Id, CloseDate, OwnerId, Account.Name from Opportunity where Id IN :opps] );
    List impToInsert = new List ();
    for( Opportunity oppo : oppsMap.values()){
        Implementation__c imp = new Implementation__c ();
        imp.Account__c = oppo.AccountId;
        imp.Name = oppo.Account.Name +' Implementation';
        imp.Phase__c = 'Phase 0';
        imp.Contract_Date__c = oppo.CloseDate;
        impToInsert.add(imp);
    }
try {
        insert impToInsert;
    } catch (system.Dmlexception e) {
        system.debug (e);
    }
    }
}
And here is the test class
@istest private class CreateImplementation {
    testMethod private static void CreateImplementation () {
        Account acco = new Account(Name = 'Acme Test Account', Type = 'Prospect');
        insert acco;
        Opportunity opp = new Opportunity(Name = 'Acme Test Opp', CloseDate=System.Today(), AccountId=acco.id, Type= 'New Business', Business_Value__c='NA',Closed_Reasons__c='NA', StageName='Closed Won',Amount=1000);
        insert opp;
        Implementation__c imp = [ SELECT Account__c, Name, Phase__c FROM Implementation__c WHERE Account__c = :acco.id LIMIT 1 ];
        System.assertEquals(imp.Phase__c,'Phase 0');
    }
}

Your answer

2 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on May 3, 2024


The error message "list index out of range" typically occurs when you're trying to access an index in a list that doesn't exist. This can happen if you're trying to access an index beyond the range of the list. Here's what you can do to address it:

Check the Length of the List: Before accessing an index in the list, verify that the list contains elements and has a length greater than zero. You can use the len() function to check the length of the list.

my_list = [1, 2, 3]
if len(my_list) > 0:
    # Access list elements safely
    print(my_list[0])

Ensure Index is Within Range: If you're accessing a specific index in the list, make sure that the index is within the valid range of indices for the list. Remember that Python uses zero-based indexing, so the first element is at index 0, the second element is at index 1, and so on.

my_list = [1, 2, 3]
if len(my_list) > 0:
    index = 2
    if index < len>

Handle Empty Lists: If you expect the list to sometimes be empty, you can add conditional checks to handle this case gracefully.

my_list = []
if len(my_list) > 0:
    # Access list elements safely
    print(my_list[0])
else:
    print("List is empty")

Error Handling: If you're expecting the list to always have elements and encountering this error indicates an unexpected condition, you can use try-except blocks to catch and handle the error.

my_list = []
try:
    # Access list elements
    print(my_list[0])
except IndexError:
    print("Index out of range or list is empty")
Was this helpful?

More Salesforce discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Salesforce Blogs

Guides, tips and career advice on Salesforce from JanBask experts.