How Do I Write an Apex Unit Test?

Question

Writing unit tests in Apex is an essential practice for ensuring code quality, maintaining stability, and meeting Salesforce’s deployment requirements. A well-written unit test follows structured principles to verify that your code behaves as expected.

Answer

Understanding Apex Unit Tests

Apex unit tests follow three essential steps:

Create test data: Before executing your code, you must create any necessary test records or data in a test context. Since tests run in isolation, they do not have access to real org data, meaning you must create mock data within the test itself.

Execute the code: The test method must call the Apex logic being tested to verify its behavior.

Write assertions: Use System.assert() or System.assertEquals() to validate that the expected results match the actual outcome.

Basic Structure of an Apex Unit Test

A simple example of a unit test for a class that updates an Account name:

Production Code to Be Tested

public class AccountHandler {
    public static void updateAccountName(Id accountId, String newName) {
        Account acc = [SELECT Id, Name FROM Account WHERE Id = :accountId LIMIT 1];
        acc.Name = newName;
        update acc;
    }
}

Explanation of the Unit Test

Creating Test Data
A new Account is created and inserted.
This ensures that there is a valid record for testing without relying on actual org data.

Executing the Code
The AccountHandler.updateAccountName() method is called with the test record’s Id.

Writing Assertions
A System.assertEquals() statement checks if the account name was successfully updated.
This ensures that the method’s logic performs as expected.

Test Isolation in Salesforce

Salesforce executes unit tests in a sandboxed, isolated environment, meaning that:

Test data does not persist after the test run. Any records created in the test method are automatically rolled back.

No access to real org data unless seeAllData=true is used (which is discouraged).

Metadata records, such as Users and Custom Metadata, are accessible in tests.

Common Mistakes to Avoid in Apex Unit Tests

1. Writing Tests Without Assertions (Smoke Tests)

A test that only runs code but does not check results is called a smoke test. These tests are not useful because they only confirm that the code does not crash, but they do not verify expected behavior.

Bad Example (Smoke Test):

@isTest
private class BadTest {
    @isTest
    static void testWithoutAssertions() {
        Account acc = new Account(Name = 'Test Account');
        insert acc;
        AccountHandler.updateAccountName(acc.Id, 'New Name');
    }
}

This test executes the method but does not verify that the name was updated correctly.

2. Using seeAllData=true (Bad Practice)

@isTest(seeAllData=true) // Avoid this!
private class BadTest {
    @isTest
    static void testUsingRealData() {
        Account acc = [SELECT Id FROM Account LIMIT 1];
        AccountHandler.updateAccountName(acc.Id, 'New Name');
    }
}

This test depends on real org data, making it fragile and inconsistent. If no records exist in the org, the test will fail. Always create test data inside the test itself.

Kick Start Your Journey with Real-Time Project-Based Salesforce Learning

Our Salesforce course is designed to provide a comprehensive understanding of the Salesforce platform, equipping you with the essential skills to excel in the CRM industry. The curriculum covers key modules like Salesforce Admin, Developer, and AI, blending theoretical learning with hands-on practice. Through real-world projects and interactive exercises, you will gain the expertise needed to tackle business challenges using Salesforce solutions. Our experienced instructors ensure you develop both technical proficiency and industry-relevant insights to thrive in the Salesforce ecosystem.

Beyond technical training, our Salesforce training in Pune offers personalized mentorship, certification guidance, and interview preparation to enhance your career prospects. You’ll have access to extensive study materials, hands-on project experience, and continuous support throughout your learning journey. By the end of the course, you’ll be fully prepared for certification exams and equipped with real-world problem-solving skills that employers seek. Take the first step toward your Salesforce career today—enroll in a Free Demo now!

0
Would love your thoughts, please comment.x
()
x