How to Write a Test Class For an Apex Trigger in Salesforce

As a Salesforce Developer, I needed to automate a process using an Apex Trigger. The trigger automatically creates a contact record whenever the sales team creates a new account for a customer.

I wrote a test class to ensure the trigger works as expected and the trigger code is error-free. This test class also verifies that the contact is created with the correct name and email.

In this tutorial, we will learn about Apex test classes and how to write a test class for an Apex Trigger in Salesforce.

What are Apex test classes in Salesforce?

In Salesforce Apex, test classes are created in the same way as an Apex class. We declare an apex class as a test class using @isTest.

The test classes in Apex ensure code quality by verifying potential issues during the test run, which is necessary when deploying the Apex code to the Salesforce org.

The test class takes parameters of expected value and actual value using System.assertEquals(expectedValue, actualValue, “message”). If both values don’t match, the test case fails; otherwise, it passes.

Example: Apex Trigger Test Class to Validate Code in Salesforce

First, I will show you the trigger code that I provided to create the related contact when a new account is created, and then I will explain how to write a test class for the trigger we created.

Write an Apex Trigger in Salesforce

Before creating the test class, I will demonstrate the apex trigger that creates a related contact record when a new account record is created, using parameters such as first name, last name, and email, and then inserts a new contact record into Salesforce.

Below is the Apex trigger code. When a new account is created, the related contact should be created with the following parameters: first name, last name, and email.

trigger CreateContactOnAccount on Account (after insert) {

    List<Contact> contactList = new List<Contact>();
    
    for (Account acc : Trigger.new) {
        if (acc.Name != null && acc.Email__c != null) {
            Contact con = new Contact(
                FirstName = acc.Name,
                LastName = 'Customer',
                Email = acc.Email__c,
                AccountId = acc.Id
            );
            contactList.add(con);
        }
    }

    if (!contactList.isEmpty()) {
        insert contactList;
    }
}

Create an Apex Test Class in Salesforce

In the following program, I created a user using the Apex test class, validating our code against the expected output and logic, as well as the values we want to insert into the Salesforce database.

In the Test class, we must add the @isTest annotation at the top of the class name. We also add this annotation before the method starts, making it a test method.

Now, to test whether the related contact is created with all values entered in user fields, we created one static method named testContactCreationFromAccountTrigger() with the @isTest annotation.

This is a static method with a return type of void because the test method should return nothing, and it should be a static method.

System.assertEquals (‘Expected Value’, Actual Value, ‘Optional Message’ ): The system class has a method called Assert. Using it, we can flag whether the test is a success or a failure while testing. 

Here, we can compare the results with the expected results of a particular test. Then,  save the program. Now, I will explain how to run the test class.

@isTest
public class Test_CreateContactOnAccount {

    @isTest
    static void testContactCreationFromAccountTrigger() {

        Account testAcc = new Account(
            Name = 'John Doe',
            Email__c = 'johndoe@example.com'
        );
        insert testAcc; 

        List<Contact> contacts = [SELECT Id, FirstName, LastName, Email, AccountId 
                                  FROM Contact 
                                  WHERE AccountId = :testAcc.Id];

        System.assertEquals('John Doe', contacts[0].FirstName, 'First name should match Account name ');

        System.assertEquals('Customer', contacts[0].LastName, 'Last name should be "Customer" ');

        System.assertEquals('johndoe@example.com', contacts[0].Email, 'Email should match Account email ');
    }
}

Run Apex Test Class on the Developer Console

To run the test class, click the Test option from the menu bar and then click the New Run option.

Create Apex Class For Triggers in Salesforce

Then select the Test class you created; as you click on it, you will see the methods you created in that test class. Now, you need to select which method you want to test. Select those methods; you can choose all if you have multiple methods.

Finally, click the Run button to execute the test class and method.

Test Class For an Apex Trigger in Salesforce

If the code has no error, the status will display a success mark.

Test the Apex Trigger in Salesforce

Now, to check whether the test failed, I changed the domain of the expected value of Email__c from ’gmail’ to ‘yahoo’ and again ran the test class as I explained in the above steps.

Now, at this time, the test class fails, and to check the error, double-click on the class name where the test class failed.

Failed Test Class in Salesforce Apex

You can see the error message explaining why the test class failed in the Error column. Now, you need to correct that error.

Run Apex Test Class in Salesforce

In this way, we can write a Test class for an Apex Trigger in Salesforce to ensure the trigger works as expected and the trigger code is error-free.

Example: Create a User Using Apex Trigger in Salesforce

In the following program, I created a user using the Apex test class, validating our code against the expected output and logic, as well as the values we want to insert into the Salesforce database.

Create a User From a Class in Salesforce

First, we need to create an Apex class to create a new user. Here, I created a class named CreateUser with a static method named createNewUser() that returns a User object. Then, write the code for creating a new user, as I explained in the above Apex program.

trigger CreateUser on User(after insert) {
    
    public static User createNewUser() {
        
        Profile profile = [SELECT Id FROM Profile WHERE Name = 'Identity User' LIMIT 1];
        
        User newUser = new User();
        
        newUser.FirstName = 'Ella';
        newUser.LastName = 'Edward';
        newUser.Email = 'ellaedward@gmail.com';
        newUser.Username = 'ellaedward@gmail.com';
        newUser.Alias = 'ellae';
        newUser.ProfileId = profile.Id;
        newUser.TimeZoneSidKey = 'America/Los_Angeles';
        newUser.LocaleSidKey = 'en_US';
        newUser.EmailEncodingKey = 'UTF-8';
        newUser.LanguageLocaleKey = 'en_US';
        
        Insert newUser;
        system.debug('User is successfully creatred');
        return newUser;
    }  
}

Create an Apex Test Class in Salesforce

Now, we will create a Test Class, for which we need to add the @isTest annotation at the top of the class name. We also add this annotation before the method starts, so it will become the test method.

Now, to test whether the user is created with all values entered in the user fields, we created one static method named testCreateUser() with the @isTest annotation. This is a static method with a return type of void because the test method should return nothing, and it should be a static method.

Then, we need to call the createNewUser() method, which we created in the CreateUser class. For that, we need to create a variable(newUser) with the data type User. Then, write SOQL to fetch user details that we will create in the above class and pass the ID using a variable.

System.assertEquals (‘Expected Value’, Actual Value, ‘Optional Message’): The system class has a method called Assert. Using it, we can flag whether the test is a success or a failure while testing. Here, we can compare the results with the expected results of a particular test.

Then, save the program. Now, I will explain how to run the test class.

@isTest
public class TsetNewUser{
      
    @isTest
    static void testCreateUser() {
        
        User newUser = CreateUser.createNewUser();
        User createdUser = [SELECT Id, FirstName, LastName, Alias, ProfileId FROM User WHERE Id 
                                         = :newUser.Id];
        System.assertEquals ('Ella', createdUser.FirstName, 'Firstname is incorrect');
        System.assertEquals ('Edward', createdUser.LastName, 'Last name is not matched');
        System.assertEquals ('ellae', createdUser.Alias); 
        //Like this add more fields that you want to test.
    }      
}

Run Apex Test Class on the Developer Console

To run the test class, click the Test option from the menu bar. Then click the New Run option.

Create New User From Text Class in Salesforce

Then select the Test class you created; as you click on it, you will see the methods you created in that test class. Now, you need to select which methods you want to test. Select those methods; you can select all if you have multiple methods.

Finally, click the Run button to execute the test class and method.

Create New User From Apex in Salesforce

If the code has no problem errors, the status will show a success mark.

Run Test Class in Salesforce Apex

Now, to check whether the test failed, I changed the expected value of the user Alias from ‘ellae’ to ‘sStark’ and ran the test class again, as I explained in the above steps.

Now, this time here, the test class fails, and to check the error, double-click on the class name where we get the test class failed.

Execute Test Class in Salesforce Apex

In the Error column, you can see the error message explaining why the test class failed. Now, you need to correct that error.

Create User from Salesforce Test Class in Apex

After successfully executing the test class, you are ready to execute the CreateUser class. Open an anonymous window and execute the class. You will see the debug statement message if a user is created.

Run Test Class in Apex

Conclusion

In this Salesforce tutorial, we learned to test an Apex Trigger using the test methods in Salesforce Apex. Following the above steps, you can test your Apex trigger using the various Apex class test methods and test your code before deploying it to the real-time environment.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.