How to Write a Test Class For an Apex Trigger in Salesforce : Bijay Kumar
by: Bijay Kumar
blow post content copied from SalesForce FAQs
click here to view original post
### Summary of the Content The content discusses the process of automating tasks in Salesforce using **Apex Triggers** and how to write **Apex Test Classes** to ensure the triggers function correctly. Specifically, it illustrates a scenario where an Apex Trigger is designed to create a contact record whenever a new account is created by the sales team. 1. **Apex Trigger**: This is a piece of code that executes before or after data manipulation language (DML) operations, such as inserting a new account. In this case, it creates a related contact for the new account. 2. **Apex Test Classes**: These are essential for verifying the correctness of the Apex code before deployment. Test classes use the `@isTest` annotation and check whether the expected output matches the actual output using assertions. 3. **Trigger Code Example**: The provided trigger code creates a contact using details from the newly created account, like name and email. 4. **Test Class Example**: The tutorial includes a test class that checks if the contact is created properly when a new account is inserted. It uses assertions to compare expected values against the actual values retrieved. 5. **Execution of Test Classes**: The content explains how to run these test classes in the Salesforce Developer Console, analyze results, and troubleshoot errors in case of failure. ### Key Details - **Apex Trigger**: Automatically creates a contact when an account is created. - **Assertions**: Used to verify that the expected results match actual results in test classes. - **Testing Process**: Involves inserting test data, running assertions, and checking for errors. - **Annotations**: The `@isTest` annotation is crucial for marking test classes and methods. ### Additional Context Understanding these concepts is crucial for Salesforce developers, as they ensure the reliability and quality of automated processes in applications. Proper testing prevents errors from reaching the production environment, which can save time and resources. ### SEO Hashtags #Salesforce #ApexTrigger #ApexTestClass #SalesforceDevelopment #SoftwareTesting #SalesforceAutomation #CodeQuality #SalesforceTutorial #DeveloperConsole #TestDrivenDevelopment
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 = '[email protected]'
);
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('[email protected]', 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.

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.

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

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.

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

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 = '[email protected]';
newUser.Username = '[email protected]';
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.

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.

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

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.

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

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.

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:
- Create and Use Constructors in Salesforce Apex Classes
- Apex Trigger Handler and Helper Class in Salesforce
- Interfaces in Salesforce Apex and How to Use it
The post How to Write a Test Class For an Apex Trigger in Salesforce appeared first on SalesForce FAQs.
May 27, 2025 at 06:55PM
Click here for more details...
=============================
The original post is available in SalesForce FAQs by Bijay Kumar
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Post a Comment