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
TanyrilTanyril 

System.QueryException: List has no rows for assignment to SObject

System.QueryException: List has no rows for assignment to SObjectClass.ClientTransBatch.testBatch: line 132, column 1

Presumeably the only part of this code that matters is the test class at the very bottom.

That's the error I'm getting from the test in this class:

 (Code removed)

 

I'm obviously doing something wrong with this test class but I can't figure out what. Can anyone help me?

Best Answer chosen by Admin (Salesforce Developers) 
crop1645crop1645

well

 

Contact con = [select Id, name from Contact where RecordTypeId= '012d0000000ebo5' LIMIT 1];

 if this is the statement in error, do you create any Contacts in the testmethod?  

 

It looks like you are expecting Contacts to be already present. They won't be unless your testmethod uses @isTest(SeeAllData=true) 

 

Using recordTypeIds hardcoded is very dangerous as they might not be the same between prod and sandbox. You should query the RecordType SObject first (using a recordTYpe Developer name as the key) to get  the ID that you can use elsewhere . This way, you are protected between sandbox and prod

 

 

All Answers

crop1645crop1645

well

 

Contact con = [select Id, name from Contact where RecordTypeId= '012d0000000ebo5' LIMIT 1];

 if this is the statement in error, do you create any Contacts in the testmethod?  

 

It looks like you are expecting Contacts to be already present. They won't be unless your testmethod uses @isTest(SeeAllData=true) 

 

Using recordTypeIds hardcoded is very dangerous as they might not be the same between prod and sandbox. You should query the RecordType SObject first (using a recordTYpe Developer name as the key) to get  the ID that you can use elsewhere . This way, you are protected between sandbox and prod

 

 

This was selected as the best answer
Devendra@SFDCDevendra@SFDC

Hi,

 

A suggestion is to, Avoid using HardCoded Ids into the test methods. As Ids can be different in different environments(except Full copy sandbox and production org)

 

Create necessary test data into the test method.

 

For e.g.

@isTest

public static void testMethod(){

    Account account = new Account(Name = 'Test Account');

    insert account;

 

    Contact contact = new Contact(AccountId= account.Id, LastName = 'TestLastName');

    insert contact;

 

    // Use the created data for further steps in test method

}

 

 

Hope this helps :)

 

THanks,

Devendra

 

TanyrilTanyril

Should have come back and told you that this was the hint I needed to get it all worked out. Thanks for your help!