Simple Apex Unit Test for Object Relationships (Account + Contacts)

Apex Unit Test for Object Relationships

Here’s a basic idea for testing Accounts and Contacts using an Apex Test Class. Since the objects are currently empty, the test will involve creating test data in the test method, which will allow you to test functionality without impacting your actual Salesforce data.

Test Scenario:

  1. Create a test Account.
  2. Create a test Contact linked to the test Account.
  3. Verify that the Contact is linked to the correct Account.
  4. Verify that the Account and Contact exist in the database.

Apex Test Class Code

@isTest
public class AccountContactTest {
    @isTest
    static void testAccountAndContactCreation() {
        // Start the test
        Test.startTest();
        
        // Step 1: Create a test Account
        Account testAccount = new Account(
            Name = 'Test Account'
        );
        insert testAccount;

        // Step 2: Create a test Contact linked to the Account
        Contact testContact = new Contact(
            FirstName = 'Test',
            LastName = 'Contact',
            Email = '[email protected]',
            AccountId = testAccount.Id
        );
        insert testContact;

        // Step 3: Retrieve the inserted Account and Contact from the database
        Account retrievedAccount = [SELECT Id, Name FROM Account WHERE Id = :testAccount.Id];
        Contact retrievedContact = [SELECT Id, FirstName, LastName, Email, AccountId FROM Contact WHERE Id = :testContact.Id];

        // Step 4: Verify that the Contact is linked to the correct Account
        System.assertEquals(testAccount.Id, retrievedContact.AccountId, 'The Contact should be linked to the correct Account.');

        // Step 5: Verify that the Account and Contact data match the expected values
        System.assertEquals('Test Account', retrievedAccount.Name, 'Account Name should match.');
        System.assertEquals('Test', retrievedContact.FirstName, 'Contact First Name should match.');
        System.assertEquals('Contact', retrievedContact.LastName, 'Contact Last Name should match.');
        System.assertEquals('[email protected]', retrievedContact.Email, 'Contact Email should match.');

        // End the test
        Test.stopTest();
    }
}

Is this test data added to actual objects?

The test data created in an Apex test class does not get added to your actual objects. Salesforce provides a built-in mechanism called test isolation that ensures:

  1. Test Data is Temporary:
    Any data created (e.g., Account or Contact records) during the execution of a test method exists only within the scope of that test.
  2. Automatic Rollback:
    Once the test completes, Salesforce automatically rolls back all changes, meaning the test data is removed and does not persist in your org. You do not need to delete test data manually; Salesforce handles it for you.

This ensures your real data remains untouched, and you can safely write and execute tests without worrying about cluttering your Salesforce environment.

A more complex Apex test code

@isTest
public class AccountContactTest {
    @isTest
    static void testAccountWithMultipleContacts() {
        // Start the test
        Test.startTest();
        
        // Step 1: Create a test Account
        Account testAccount = new Account(
            Name = 'Mock Account',
            Industry = 'Finance',
            AnnualRevenue = 500000
        );
        insert testAccount;

        // Step 2: Create multiple test Contacts linked to the Account
        List<Contact> mockContacts = new List<Contact>{
            new Contact(FirstName = 'Alice', LastName = 'Johnson', Email = '[email protected]', AccountId = testAccount.Id),
            new Contact(FirstName = 'Bob', LastName = 'Smith', Email = '[email protected]', AccountId = testAccount.Id),
            new Contact(FirstName = 'Charlie', LastName = 'Brown', Email = '[email protected]', AccountId = testAccount.Id)
        };
        insert mockContacts;

        // Step 3: Retrieve the Account and associated Contacts
        Account retrievedAccount = [SELECT Id, Name, Industry, AnnualRevenue FROM Account WHERE Id = :testAccount.Id];
        List<Contact> retrievedContacts = [SELECT Id, FirstName, LastName, Email, AccountId FROM Contact WHERE AccountId = :testAccount.Id];

        // Step 4: Perform assertions on Account fields
        System.assertEquals('Mock Account', retrievedAccount.Name, 'Account Name should match.');
        System.assertEquals('Finance', retrievedAccount.Industry, 'Industry should match.');
        System.assertEquals(500000, retrievedAccount.AnnualRevenue, 'Annual Revenue should match.');

        // Step 5: Perform assertions on the associated Contacts
        System.assertEquals(3, retrievedContacts.size(), 'There should be 3 Contacts linked to the Account.');

        // Validate each contact's data
        Map<String, String> expectedContacts = new Map<String, String>{
            'Alice Johnson' => '[email protected]',
            'Bob Smith' => '[email protected]',
            'Charlie Brown' => '[email protected]'
        };

        for (Contact retrievedContact : retrievedContacts) {
            String contactFullName = retrievedContact.FirstName + ' ' + retrievedContact.LastName;
            System.assert(expectedContacts.containsKey(contactFullName), 'Unexpected contact: ' + contactFullName);
            System.assertEquals(expectedContacts.get(contactFullName), retrievedContact.Email, 'Email should match for ' + contactFullName);
        }

        // End the test
        Test.stopTest();
    }
}

Explanation of the Code

  1. Mock Data Creation:
    • Creates one Account with mock data, including Name, Industry, and AnnualRevenue.
    • Creates three Contact records linked to the Account using the AccountId.
  2. Data Retrieval:
    • Retrieves the Account and its associated Contact records using SOQL queries.
  3. Assertions:
    • Validates the fields on the Account (Name, Industry, AnnualRevenue).
    • Ensures that exactly three Contact records are linked to the Account.
    • Uses a Map<String, String> to validate each contact’s full name (FirstName + LastName) and email.
  4. Test Isolation:
    • All records are rolled back after the test execution to prevent changes to the database.
  5. Dynamic Validation:
    • The loop checks that each retrieved contact matches the expected name and email stored in the Map.
Scroll to Top