How to write Test Classes in Salesforce?
Updated on 10th Oct, 23 9.2K Views

Salesforce allows users to make their test classes; approximately 75 percent of the code is covered by the test classes only. This is done to make sure that there are no issues in the Salesforce Dashboard during production. Test classes allow testing the logic for Apex triggers, Apex classes, Visualforce Controller, Visualforce Extensions, Batch Apex, Queueable Apex, and Future Apex.

Watch the Salesforce training video and learn all about Salesforce.

What is a Test Class in Salesforce?

In Salesforce, a test class is a class that is used to test the functionality of another class, usually an Apex class, trigger, or web service. Test classes are written in Apex and are used to verify that the code written by developers works as intended before it is deployed to a production environment. Test classes are not counted in code coverage before they get deployed by the Salesforce Admin in final production.

Test classes in Salesforce allow about 75 percent code coverage, which means more than half of the testing work is completed by the test classes themselves. They work similarly to Python testing, where the written code is tested by a just-in-time compiler performing the testing.

Test Methods

Let us take a look at some of the test methods:

1. createStub(parentType, stubProvider)

  • Description: It creates a stubbed version of an Apex class and can be used with the System.StubProvider interface to build a mocking framework. 
  • Usage: It works with the System.StubProvider interface. It defines the behavior of the stubbed object by using the StubProvider interface. 

2. enableChangeDataCapture()

  • Description: It is in an Apex test to generate change event notifications for all supported Change Data Capture entities. 
  • Usage: It ensures that Apex tests can fire change event triggers.

3. enqueueBatchJobs(numberOfJobs)

  • Description: It adds the specified number of jobs with no-operation contents to the test-context queue.
  • Usage: It is used to reduce testing time. It can be used to simulate batch-job enqueuing instead of using real batch jobs for testing.

4. getEventBus()

  • Description: It returns an instance of the test event bus broker that allows operation on platform events or changes event messages in an Apex test.
  • Usage: It encloses Test.getEventBus().deliver() within the Test.startTest() and Test.stopTest() statement block.

5. getFlexQueueOrder()

  • Description: It returns an ordered list of job IDs for jobs in the test-context flex queue. 
  • Usage: This method retrieves the job IDs in the flex queue for testing purposes.

6. getStandardPricebookId()  

  • Description: It returns the ID of the standard price book in the organization.
  • Usage: It returns the ID of the standard price book regardless of whether the test can query organization data. 

7. invokeContinuationMethod(controller, request)  

  • Description: It activates the callback method for the specified controller and continues in a test method.
  • Usage: Use the Test.setContinuationResponse and Test.invokeContinuationMethod methods to test continuations. Test.setContinuationResponse.

8. isRunningTest()  

  • Description: It is used if different code needs to be run depending on whether it was being called from a test.
  • Usage: This method facilitates identifying whether the code is executing within a testing environment.

9. loadData(sObjectToken, resourceName)

  • Description: It inserts test records from the specified static resource .csv file for the specified sObject type and returns a list of the inserted sObjects.
  • Usage: The method requires a pre-created static resource in CSV format with field names and values for test records. The static resource must have the MIME type assigned as text/csv, application/vnd.ms-excel, or application/octet-stream.

10. newSendEmailQuickActionDefaults(contextId, replyToId)

  • Description: It creates a new QuickAction.
  • Usage: This method is utilized to create a new QuickAction object that is pre-configured for sending emails, including default values for context and reply-to IDs.

11. setContinuationResponse(requestLabel, mockResponse)

  • Description: It sets a mock response for a continuation HTTP request in a test method.
  • Usage: To test continuations in Salesforce, use Test.setContinuationResponse and Test.invokeContinuationMethod methods. These methods allow setting a mock response and executing the associated callback method to process the response during testing. 

12. setCreatedDate(recordId, createdDatetime)

  • Description: It sets CreatedDate for a test-context sObject.
  • Usage: In Salesforce tests, all database changes are reverted at the end, and this method cannot be used on pre-existing records. The setCreatedDate should be called after inserting the test record and should not have a future date to avoid unexpected outcomes.

13. setCurrentPage(page)

  • Description: It sets the current PageReference for the controller.
  • Usage: –This method establishes the controller’s current PageReference object.

14. setCurrentPageReference(page)

  • Description: It sets the current PageReference for the controller.
  • Usage: This method assigns the provided PageReference object as the current page reference for the controller.

15. setFixedSearchResults(fixedSearchResults)

  • Description: It defines a list of fixed search results to be returned by all subsequent SOSL statements in a test method.
  • Usage: All subsequent SOSL queries return no results if opt_set_search_results is not specified.

16. setMock(interfaceType, instance)

  • Description: It sets the response mock mode and instructs the Apex runtime to send a mock response in case of a callout made through the HTTP classes or the auto-generated code from WSDLs.
  • Usage: To mock a callout, if the code that performs the callout is in a managed package, call Test.setMock from a test method in the same package with the same namespace.

17. setReadOnlyApplicationMode (applicationMode)

  • Description: It sets the application mode to read-only to simulate read-only mode during Salesforce upgrades and downtimes. The application mode is reset to the default mode at the end of each test run.
  • Usage: Do not use setReadOnlyApplicationMode for purposes unrelated to read-only-mode testing, such as simulating DML exceptions.

18. startTest()

  • Description: It marks the point in a test code when the test actually begins. This method is used when the governor limits are being tested.
  • Usage: To ensure proper asynchronous call execution before assertions, use stopTest() after startTest(). Only one stopTest() call is allowed per test method, and any code between these calls is subject to a new set of governor limits.

19. stopTest()

  • Description: It marks the point in the test code when the test ends. This method is used with the startTest method.
  • Usage: The stopTest() method allows calling it once per test method, and any code after it reverts to the original limits. It ensures that asynchronous calls made after startTest() are executed synchronously.

20. testInstall(installImplementation, version, isPush)

  • Description: It tests the use of the InstallHandler interface, which is used for specifying a post-install script in packages. 
  • Usage: It throws a run-time exception if the test install fails.

21. testSandboxPostCopyScript(script, organizationId, sandboxId, sandboxName)

  • Description: It tests the implementation of the *** used for specifying a script to run at the completion of a sandbox copy. 
  • Usage: It throws a run-time exception if the test install fails.    

22. estUninstall(uninstallImplementation)

  • Description: It tests the implementation of the UninstallHandler interface, which is used for specifying an uninstall script in packages. 
  • Usage: It throws a run-time exception if the test uninstall fails.

Look at the Salesforce Certification Training in Bangalore provided by Intellipaat!

Salesforce Master Course

How Do We Write a Test Class in Salesforce?

The following are the steps to create a test class in Salesforce:

Step 1 – Firstly, open the Salesforce dashboard

Step 2 – On the Quick Find tab, search Apex Classes

Step 3 – Click on New to select a new Apex Class

Step 4 – In this, add the test class definition

Step 5 – This is the syntax

@isTest
private class MyTestClass {
    @isTest static void myTest() {
        // code_block
    }
}

Want to become a certified Salesforce professional? Check out our Salesforce Certification Training.

Step 6 – Your code will look somewhat like this depending on the object and trigger you have created in your Salesforce account. This is one of the examples of test classes in Salesforce

Step 7 –  You require to run this code in the developer’s console and after that, put your custom-designed apex class code into the console

Step 8 – Run this code to test your output in the console

Step 9 – Select the test class that you want to run

Step 10 – To add all methods in the test class to the test run, click Add Selected

Step 11 – Click Run

Step 12 – The test result is displayed in the Tests tab. Optionally, you can expand the test class in the Tests tab to view which methods were run. In this case, the class contains only one test method.

Your Test Class is created.

Are you practicing for a Salesforce interview? Check out our Top Salesforce Interview Questions and Answers.

Benefits of Test Classes in Salesforce

The following are some of the benefits of test classes in Salesforce:

  • Reduces the bug cost, i.e., it helps in troubleshooting
  • Performs bulk tests at a time
  • Ensures desired output to the user
  • Delivers high-quality apps to the production organization, making production users more productive

Want to know more about Salesforce? Read this extensive Salesforce Tutorial and enhance your knowledge!

Get 100% Hike!

Master Most in Demand Skills Now !

Annotations of Test Class in Salesforce

The following are some of the annotations used in a test class in Salesforce:

  • @isTest: It is used at the class or method level to indicate that it contains only the test coverage code. Classes defined with this annotation do not count toward your organization’s Apex code limits.
  • @testSetup: It indicates the specific method used to set the test data. If @testSetup is specified, it will be executed before any other method in the test class. Regardless of how other test methods use the data, each test method can access the original generated test dataset.
  • @testVisible: When creating Apex logic, it makes sense to define elements such as methods, variables, and internal classes as private or protected.

However, this can make test coverage difficult. Fortunately, Salesforce took care of the future and provided us with @testVisible annotations.

Using this annotation on private or protected members allows access to test classes but maintains the visibility defined for non-test classes.

  • @isTest(See all Data=True): Salesforce test class should be responsible for creating its own data. However, sometimes you need to access existing data, and using @isTest (SeeAllData=True) can provide access to your test classes and test methods.

Available since API 24.0, there are some precautions for using @isTest (SeeAllData=True). SeeAllData=True can be used at the class and method level. When SeeAllData=True is at the class level, all methods can access the existing data, but when SeeAllData=True is at the method level, these methods can only access the existing data.

Finally, using SeeAllData=False at the method level will not override the SeeAllData=True used at the class level.@isTest(isParallel=True): Use the

  • @isTest(isParallel=true) annotation to take a look at the categories that may run in parallel. Default limits on the number of coinciding tests do not apply to those test classes.

Are you preparing for a Salesforce admin interview? Check out our Top Salesforce Admin Interview Questions and Answers.

Best Practices for Test Classes in Salesforce

Some rules for writing test classes in Salesforce are the following:

  • Always start with @is Test annotations to make Salesforce understand that you are writing a test class.
  • Always keep the class private; try to name it as the original class or trigger name.
  • The methods of your test class have to be static; the void and testMethod keywords have to be used.
  • Use Test.startTest() and Test.stopTest () to ensure that the actual testing of the code is done using a new set of governor constraints. These methods can help you reset the governor limits before running the test code.
  • Once your test code runs between Test.startTest() and Test.stopTest(), you need to use assert statements to check whether or not your actual code is executed and gives the results as expected.

In your case, you tend to test whether the book’s worth has been set to 90 or not. If this assert statement returns false, your test category will fail and let you know that one thing is not correct in your code, and you should repair your original code.

  • When a deadlock occurs in tests that are running in parallel, they try to create records with duplicate index field values. A deadlock occurs when two running tests wait for each other to roll back their data. Such a wait can happen if two tests insert records with the same unique index field values in different orders.

Conclusion

As discussed earlier, more than half of the testing work is executed by the test classes. Therefore, it is vital for anyone who wants to test the logic for Apex triggers, Apex classes, Visualforce Controllers, Queueable Apex, Future Apex, Visualforce Extensions, and Batch Apex to know how to create test classes. We hope this blog gives you an idea of how test classes in Salesforce are used, along with all the different test methods that can be implemented in Salesforce.

Do you have any more queries regarding Salesforce developer jobs? Join our Salesforce Community page and get your queries answered.

Career Transition

Testing to Salesforce Career Transtition | Got Job Offers With 90% of Salary Hike | Intellipaat
Intellipaat Reviews - Salesforce Training | Career Transition to Salesforce Marketing Cloud Admin
Salesforce Admin To Salesforce Developer | Got Job With Salary Hike | Intellipaat Career Transition
Intellipaat Reviews - Salesforce Training | Career Transition | Got a New Job With 100% Salary Hike
Got Job As a Salesforce Developer at Ericsson with Salary Hike | Intellipaat Career Transition
How to become a Salesforce Admin | Got Job Just After 1 Month | Intellipaat Career Transition

Course Schedule

Name Date Details
Salesforce Certification 24 Feb 2024(Sat-Sun) Weekend Batch
View Details
Salesforce Certification 02 Mar 2024(Sat-Sun) Weekend Batch
View Details
Salesforce Certification 09 Mar 2024(Sat-Sun) Weekend Batch
View Details

Speak to our course Advisor Now !

Related Articles

Subscribe to our newsletter

Signup for our weekly newsletter to get the latest news, updates and amazing offers delivered directly in your inbox.