Apex test: Create test data and retrieve it with SOQL query

Apex test Create test data and retrieve it with SOQL query

Below is an example of an Apex test class that creates and retrieves test data using SOQL queries. No custom objects or fields are used, so this example works with standard Salesforce objects like Account and Contact.

@isTest
public class SOQLTestClass {
    // This test method will focus on creating data and retrieving it with SOQL.
    @isTest
    static void testSOQLQueries() {
        // Step 1: Create test data
        List<Account> accounts = new List<Account>();
        for (Integer i = 1; i <= 5; i++) {
            accounts.add(new Account(Name = 'Test Account ' + i));
        }
        insert accounts;

        List<Contact> contacts = new List<Contact>();
        for (Integer i = 1; i <= 5; i++) {
            contacts.add(new Contact(LastName = 'Test Contact ' + i, AccountId = accounts[0].Id));
        }
        insert contacts;

        // Step 2: Retrieve data using SOQL
        List<Account> retrievedAccounts = [SELECT Id, Name FROM Account WHERE Name LIKE 'Test Account%'];
        System.assertEquals(5, retrievedAccounts.size(), 'There should be 5 test accounts retrieved.');

        List<Contact> retrievedContacts = [SELECT Id, LastName, Account.Name FROM Contact WHERE Account.Name = :accounts[0].Name];
        System.assertEquals(5, retrievedContacts.size(), 'There should be 5 contacts related to the first account retrieved.');

        // Validate specific data
        for (Contact contact : retrievedContacts) {
            System.assert(contact.LastName.startsWith('Test Contact'), 'Contact LastName should start with "Test Contact".');
        }

        // Step 3: Cleanup (not necessary in test context as test data is rolled back)
    }
}

What does this test feature:

Test Data Creation:

  • Five Account records are created with names Test Account 1 to Test Account 5.
  • Five Contact records are created, all linked to the first Account (to test relationship queries).

SOQL Queries:

  • First SOQL retrieves all accounts whose names start with Test Account.
  • Second SOQL retrieves all contacts associated with the first account using the relationship field Account.Name.

Assertions:

  • The test validates that the expected number of records is retrieved.
  • It also verifies that the Contact records’ LastName follow the expected naming convention.

Cleanup:

  • You don’t need to delete test data in test methods because Salesforce rolls back all changes after the test execution.

Scroll to Top