This is the first time I have messed with test classes, so there may be something I am simply overlooking. However, I am trying to test a simple class but am only getting an out of bounds exception as a result of the SOQL statement returning blank. After plugging the same SOQL statement into the developer console, I receive what was originally expected. Thanks for the help, I'll leave the little code that I'm referring to below.

public static List<Tactic_Contact__c> searchTacticContacts(String PCID)
    List<Tactic_Contact__c> startList = [SELECT Tactic_Name__c, Tactic_Contact__c.Project_Contact__r.Name FROM Tactic_Contact__c WHERE Tactic_Contact__c.Project_Contact__r.Name = :PCID];
    return startList;
static void searchTacticContactsTest()
    List<Tactic_Contact__c> TList = (RelatedContacts.searchTacticContacts('PCID-063815'));
    System.assertEquals('PCID-063815', TList.get(0).Project_Contact__r.Name);

1 Answer 1


In unit tests, there are 3 phases.

  1. Create test data
  2. Execute the method you want to test
  3. Gather the results, and make assertions

You're doing #2 and #3, but you've skipped over #1.

You are responsible for creating the data that your test needs (so that it can run). Tests are run isolated from "real" data by default, and this is a good thing. The exception to this is data for "setup objects" like User, Profile, RecordType, and a handful of others, which are available in tests without needing to do anything on your part.

So in this case, you need to:

  • Create a test Contact and insert it
  • Create a test Tactic_Contact__c record, relate it to your test Contact, and insert it

Then, you'll be able to call the method you want to test, RelatedContacts.searchTacticContacts()

  • The next things you should look at after this are: 1) Use a @testSetup annotated method to handle setting up the test data. Not a big issue for this test, but it's a good habit to get into. 2) Make more tests! Testing a lot of different scenarios helps ensure that your code is robust, and will naturally lead to high coverage. I'd definitely suggest making a specific test for when your query returns 0 rows (the list you get back should be empty and you shouldn't run into any exceptions).
    – Derek F
    Jun 27 at 17:05
  • Works great, thank you very much. I'll be sure to do more reading on the subject. Thank you for pointing me in the right direction.
    – JLadage
    Jun 27 at 17:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.