Unit Testing in Salesforce Apex: A Detailed Tutorial

Unit testing is a crucial part of the development process in Salesforce Apex. It helps ensure that your code works as expected and prevents future regressions when changes are made. This tutorial will cover the basics of unit testing in Salesforce Apex, with examples and code snippets to illustrate the concepts.

Table of Contents

  1. Introduction to Unit Testing
  2. Creating Test Classes and Methods
  3. Test Data Setup
  4. Using System.assert Statements
  5. Test Isolation and Best Practices
  6. Code Coverage Requirements
  7. Running Tests and Viewing Results
  8. Examples

Introduction to Unit Testing

Unit testing involves writing test methods that verify the functionality of your code by checking the output of methods against expected results. In Salesforce, unit tests are written in Apex and are executed using the built-in testing framework.

Creating Test Classes and Methods

In Salesforce, test classes and methods are annotated with @isTest. This annotation marks the class or method as a test that will not count against your organization’s code limits.

Test Class Structure

@isTest
private class MyTestClass {
    @isTest
    static void myTestMethod() {
        // Test logic goes here
    }
}

 

Example

@isTest
private class AccountServiceTest {
    @isTest
    static void testCreateAccount() {
        // Test logic goes here
    }
}

 

Test Data Setup

Salesforce requires that you create test data within your test methods. This ensures that your tests do not depend on the data in your organization and are isolated from changes to that data.

Example

@isTest
private class AccountServiceTest {
    @isTest
    static void testCreateAccount() {
        // Create test data
        Account acc = new Account(Name = 'Test Account');
        insert acc;

        // Verify the account was created
        Account insertedAccount = [SELECT Id, Name FROM Account WHERE Id = :acc.Id];
        System.assertEquals('Test Account', insertedAccount.Name);
    }
}

Using System.assert Statements

System.assert statements are used to verify that the actual results of your code match the expected results.

Example

@isTest
private class AccountServiceTest {
    @isTest
    static void testCreateAccount() {
        // Create test data
        Account acc = new Account(Name = 'Test Account');
        insert acc;

        // Verify the account was created
        Account insertedAccount = [SELECT Id, Name FROM Account WHERE Id = :acc.Id];
        System.assertEquals('Test Account', insertedAccount.Name);
        System.assertNotEquals(null, insertedAccount.Id);
    }
}

Test Isolation and Best Practices

  • Use Test.startTest() and Test.stopTest(): These methods help reset governor limits within your test methods, ensuring that your tests do not exceed Salesforce’s limits.
  • Test for Positive and Negative Scenarios: Ensure that your code handles both expected and unexpected inputs.
  • Use @testSetup: This annotation allows you to create common test data that can be shared across multiple test methods within a class.

Example

@isTest
private class AccountServiceTest {
    @testSetup
    static void setup() {
        Account acc = new Account(Name = 'Test Account');
        insert acc;
    }

    @isTest
    static void testCreateAccount() {
        // Use the test data created in @testSetup
        Account insertedAccount = [SELECT Id, Name FROM Account WHERE Name = 'Test Account'];
        System.assertEquals('Test Account', insertedAccount.Name);
    }
}

Code Coverage Requirements

Salesforce requires at least 75% code coverage for deployment to production. This means that your test methods must cover at least 75% of the lines of code in your organization.

Running Tests and Viewing Results

You can run tests in Salesforce using the Developer Console, the Setup menu, or Salesforce DX. After running tests, you can view the results to see which tests passed or failed and the amount of code coverage achieved.

Running Tests in the Developer Console

  1. Open the Developer Console.
  2. Click on Test > New Run.
  3. Select the test classes you want to run.
  4. Click Run.

Viewing Results

  1. Open the Developer Console.
  2. Click on Test > Test Runner.
  3. View the results in the Test Runner tab.

Examples

Example 1: Testing a Trigger Handler

Suppose you have a trigger handler that updates a custom field on an account when it is created.

public class AccountTriggerHandler {
    public static void onAfterInsert(List<Account> newAccounts) {
        for (Account acc : newAccounts) {
            acc.Custom_Field__c = 'Updated';
        }
        update newAccounts;
    }
}

 

Test Class

@isTest
private class AccountTriggerHandlerTest {
    @isTest
    static void testOnAfterInsert() {
        // Create test data
        Account acc = new Account(Name = 'Test Account');
        insert acc;

        // Verify the custom field was updated
        Account insertedAccount = [SELECT Id, Name, Custom_Field__c FROM Account WHERE Id = :acc.Id];
        System.assertEquals('Updated', insertedAccount.Custom_Field__c);
    }
}

Example 2: Testing a Service Class

Suppose you have a service class that creates a new account.

public class AccountService {
    public static Account createAccount(String name) {
        Account acc = new Account(Name = name);
        insert acc;
        return acc;
    }
}

 

Test Class

@isTest
private class AccountServiceTest {
    @isTest
    static void testCreateAccount() {
        // Call the service method
        Account acc = AccountService.createAccount('Test Account');

        // Verify the account was created
        Account insertedAccount = [SELECT Id, Name FROM Account WHERE Id = :acc.Id];
        System.assertEquals('Test Account', insertedAccount.Name);
    }
}

Conclusion

Unit testing in Salesforce Apex is a powerful way to ensure the reliability and maintainability of your code. By following best practices and writing comprehensive tests, you can catch bugs early and make future development more efficient. Use the examples and guidelines provided in this tutorial to start writing effective unit tests in your Salesforce projects.

Leave a Comment