Testing is one of the key components in the development phase. It plays a key role in running successful long-term development of an organization. It helps to identify the errors, any missing requirements, verifies whether the actual result matches the expected result and facilitates to develop the error-free code. So, testing is equally important as development in every application.
Similarly, Apex testing is a critical component in Salesforce as all the development work must be done in either sandbox or developer edition and then deploy into production as we cannot develop any apex code in a production environment. In this article, we will be explaining the overview of apex testing, best practices, and an apex trigger test example.
Overview of Salesforce Apex Unit Testing
In Salesforce, Apex provides a testing framework to perform a unit testing of the triggers in Salesforce and classes which allows writing test classes, run, check test results, and to verify the functionality of the code works as expected. And it also generates the code coverage results which can be defined as the number of lines in the triggers or classes have been executed by the test methods in the test classes. In order to deploy the apex code from sandbox to production, the code must have 75% code coverage.
It is a best practice to cover all functionalities with positive and negative, single and bulk record test cases rather than focusing on 75% of the code to be covered. And the test data is not saved into the database. The test classes can be run in Salesforce user interface, Force.com IDE, or using API.
Best Practices of Apex testing
- Use @isTest annotation at the beginning of a class to declare it as a test class.
- Please make sure to generate a minimum of 75% code coverage to deploy into production and try to cover all the positive and negative use cases.
- Use System.assert() to verify that the code works as expected.
- Use System.runas() to test the functionality in user context.
- Use Test.start() and Test.stop() which contains a test call which will fire a trigger. It provides a separate governor limit to the block of the code in these methods.
- Only one Test.start() and Test.stop() can be used in one test method.
Example of Apex Trigger Test
Consider a contact trigger “RestrictContactByInvalidName” which blocks inserting and updating of any contact with the last name as ‘INVALIDNAME’. Now, this trigger is tested with our test class “TestRestrictContactByInvalidName”.
Below is the Apex code to restrict the contact by invalid name.
- The below code is an Apex code to restrict the contact from creating or updating of invalid last name.
trigger RestrictContactByInvalidName on Contact (before insert,before update) { For (Contact c : Trigger.New) { if(c.LastName == 'INVALIDNAME') { //invalidname is invalid c.AddError('The Last Name "'+c.LastName+'" is not a valid name'); } } }
Now, write the apex test class for the above “RestrictContactByInvalidName” trigger. Follow the below steps to add and run the test class for the trigger.
-
- Open the developer console, click on File | New | Apex Class.
- Enter TestRestrictContactByInvalidName for the class name, and then click OK.
- Write the below apex code by replacing the default class body.
- The below code is an Apex test class to restrict the contact from creating or updating of invalid last name.
@isTest public class TestRestrictContactByInvalidName { static testMethod void validName() { Account acc = new Account(); acc.Name = 'Test Customer'; insert acc; test.startTest(); Contact cnct = new Contact(); cnct.FirstName = 'Insert'; cnct.LastName = 'Contact'; cnct.AccountId = acc.Id; insert cnct; List<Contact> cnctList = [SELECT Id FROM Contact WHERE AccountId = :acc.Id]; system.assertEquals(1,cnctList.size()); test.stopTest(); } static testMethod void invalidName() { Account acc = new Account(); acc.Name = 'Test Customer'; insert acc; test.startTest(); Contact cnct = new Contact(); cnct.FirstName = 'Insert'; cnct.LastName = 'INVALIDNAME'; cnct.AccountId = acc.Id; insert cnct; List<Contact> cnctList = [SELECT Id FROM Contact WHERE AccountId = :acc.Id]; system.assertEquals(0,cnctList.size()); test.stoptest(); } }
Explanation of the APEX Code
-
- Line 1, @IsTest annotation is used to declare a class as a test class.
- Line 3, test method keyword is used before a method which doesn’t take any parameters, does not save any test data to the database, and will not send any emails.
- Line 7 and 16, test.startTest() and test.stopTest() are used to write the block of code which will fire the trigger.
- Line 15, assertEquals() to check the desired results.
To run the tests, follow the below steps.
-
- Open the developer console, click on Test | New Run
- Under Test Classes, select all the methods under that class. Click on Run.
- In the test tab, we can see the results of the test as they are running.
- In the above screenshot, the test run reports one failed method. To get more details about the failure, double-click the test run.
- The test method is failed because the last name of the contact is “INVALIDNAME”. So, “RestrictContactByInvalidName” trigger throws an error message.
- And after running the tests, code coverage will be automatically generated for all the triggers and classes.
In this way, we can run unit tests for triggers and classes as it is very important for deploying into the production environment in Salesforce and also to verify and validate the apex code. And we sincerely hope that this was useful and any comment of feedback will be very helpful.
How we can help
Our team can help you customize and integrated Salesforce as per your business process. Read about our Salesforce Integration Services. Reach out to us for a free assessment of your business needs.