0

How can I retrieve data as a string from a SOQL query?

The code I have below gives an error: "System.ListException: List index out of bounds: 0" If a run a check through Query Editor or even ExecuteAnonymous, I can see the data that I'm looking for exists. The tests indicate that the list created by the SOQL query is not empty, but for some reason will not let me select the first value.

public class SurveyUtilityTest {
    static testMethod void testParse() {
        List<Survey__c> surList = [SELECT Name, Full_Survey_Response__c 
                                    FROM Survey__c WHERE Name = 'test' LIMIT 1];
        if (surList != null){
            String json = String.valueOf(surList[0].get('Full_Survey_Response__c'));
            System.Assert(json != null);                        
        } else {
            System.Assert(surList == null);
        }
    }
}

3 Answers 3

0

A query never returns a null result. If there are no values, the list will be empty, instead.

if(!surList.isEmpty()) {
  String jsonString = surList[0].Full_Survey_Response__c;
} else {
  // Do something here
}
1
  • I have adjusted the code to change the if statement. I am still receiving the error "System.ListException: List index out of bounds: 0"
    – user123801
    Commented Nov 25, 2022 at 16:20
0

Your testmethod isn't testing any underlying code. Presumably, you would have something like this:

// Given some mocked data (if any)
...

Test.startTest();
// when code-under-test invoked
new someObject().doSomething();
Test.stopTest();

// then verify survey created with JSON data
List<Survey__c> surList = [SELECT Name, Full_Survey_Response__c 
                                FROM Survey__c WHERE Name = 'test' ];
System.assert(!surList.isEmpty(),'should be at least 1 survey');
System.assertNotEquals(null,surList[0].Full_Survey_Response__c, 'should be some json here');
2
  • I am aware that the test method isn't testing any underlying code. While I am still working on building the code, I had originally had the test data hard-coded, but found that the json was too long and causing issues. I was hoping to use the SOQL query to retrieve the data instead since this is how the code will be done ultimately. I am still receiving the errot that "System.ListException: List index out of bounds: 0"
    – user123801
    Commented Nov 25, 2022 at 16:22
  • list index out of bound: 0 means surList is empty, probably because you don't have a @testsetup method to mock some sample Survey__c. testmethods don't have access to org data
    – cropredy
    Commented Nov 25, 2022 at 21:12
0

SOQL query should not be run to populate data in a Test class. It can only be done if the permission of the data is given @isTest(SeeAllData=true) - which isn't recommended. Discussion here.

It is necessary to write the expected data in the test class as a new record and insert it in the setup.

You must log in to answer this question.