How to write Test Classes in Salesforce?
Updated on 11th Mar, 22 265 Views

Salesforce allows users to make their own 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 Salesforce Dashboard during the production. Test classes allow testing the logic for Apex triggers, Apex class, Visualforce Controller, Visualforce Extensions, Batch Apex, Queueable Apex, and Future Apex.

Watch the video and learn all about Salesforce

What is Test Class in Salesforce?

The work of test classes in Salesforce is basically to check whether every logic is working as it has to or it can be positive or negative testing. Test classes are not counted in code coverage before it gets deployed by the Salesforce admin in the final production.

Test classes in Salesforce allow about 75 percent of code coverage, which means more than half of the testing work is completed by the test classes themselves. They work similar 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:

Test MethodsDescriptionUsage
clearApexPageMessages()  It clears the messages on a Visualforce page while executing Apex test methods.It may only be used in tests.
createStub(parentType, stubProvider)It creates a stubbed version of an Apex class and can be used with the System.StubProvider interface to build a mocking framework. This method is also a part of the Apex stub API.It works with the System.StubProvider interface. Define the behavior of the stubbed object by using the StubProvider interface. Then create a stubbed object using the createStub() method. When methods are invoked on the stubbed object, the handleMethodCall() method of the StubProvider interface is called to perform the behavior of the stubbed method.
enableChangeDataCapture()It is in an Apex test so that change event notifications are generated for all supported Change Data Capture entities. This method is called at the beginning of the test before performing DML operations and calling Test.getEventBus().deliver();.It ensures that Apex tests can fire change event triggers regardless of the entities selected in Setup in the Change Data Capture page. The enableChangeDataCapture() method does not affect the entities that are selected in Setup.
enqueueBatchJobs(numberOfJobs)It adds the specified number of jobs with no-operation contents to the test-context queue. It first fills the test batch queue up to a maximum of five jobs and, then, places jobs in the test flex queue, with 100 jobs being the limit.It is used to reduce testing time. It can be used to simulate batch-job enqueueing instead of using real batch jobs for testing. Using this method is faster than enqueuing real batch jobs.
getEventBus()It returns an instance of the test event bus broker that allows operation on platform events or change event messages in an Apex test.Enclose Test.getEventBus().deliver() within the Test.startTest() and Test.stopTest() statement block.
getFlexQueueOrder()Returns an ordered list of job IDs for jobs in the test-context flex queue. The job at Index 0 is the next job slated to run. This method only returns test-context results.
getStandardPricebookId()  It returns the ID of the standard price book in the organization.It returns the ID of the standard price book regardless of whether the test can query organization data. By default, tests cannot query organization data unless they are annotated with @isTest(SeeAllData=true). Creating price book entries with a standard price requires the ID of the standard price book.
invokeContinuationMethod(controller, request)  It invokes the callback method for the specified controller and continuation in a test method.Use the Test.setContinuationResponse and Test.invokeContinuationMethod method to test continuations. In test context, callouts of continuations are not sent to the external service. By using these methods, a mock response can be set and the runtime to call the continuation callback method to process the mock response can be caused. Call Test.setContinuationResponse before calling Test.invokeContinuationMethod. When Test.invokeContinuationMethod is called, the runtime executes the callback method that is associated with the continuation. The callback method processes the mock response that is set by Test.setContinuationResponse.
isRunningTest()  It is used if different code needs to be run depending on whether it was being called from a test.
loadData(sObjectToken, resourceName)It inserts test records from the specified static resource .csv file and for the specified sObject type and returns a list of the inserted sObjects.The static resource must be created prior to calling this method. The static resource is a comma-delimited file ending with a .csv extension. The file contains field names and values for the test records. The first line of the file must have the field names, and subsequent lines are the field values.   Once a static resource for a .csv file is created, it will be assigned an MIME type: text/csvapplication/vnd.ms-excelapplication/octet-streamtext/plain
newSendEmailQuickActionDefaults(contextId, replyToId)It creates a new QuickAction.SendEmailQuickActionDefaults instance for testing a class using the QuickAction.QuickActionDefaultsHandler interface.
setContinuationResponse(requestLabel, mockResponse)It sets a mock response for a continuation HTTP request in a test method.Use the Test.setContinuationResponse and Test.invokeContinuationMethod method to test continuations. In test context, callouts of continuations are not sent to the external service. By using these methods, a mock response can be set. The usage of these methods can also cause the runtime to call the continuation callback method to process the mock response. Call Test.setContinuationResponse before you call Test.invokeContinuationMethod. When you call Test.invokeContinuationMethod, the runtime executes the callback method that is associated with the continuation. The callback method processes the mock response that is set by Test.setContinuationResponse.  
setCreatedDate(recordId, createdDatetime)It sets CreatedDate for a test-context sObject.All database changes are rolled back at the end of a test. This method cannot be used on records that existed before the test was executed. setCreatedDate can also not be used in methods annotated with @isTest(SeeAllData=true), because those methods have access to all data in the organization. If the CreatedDate is set to a future value, it can cause unexpected results. This method takes two parameters—an sObject ID and a Datetime value—neither of which can be null. Insert the test record before its CreatedDate is set.  
setCurrentPage(page)It sets the current PageReference for the controller.
setCurrentPageReference(page)It sets the current PageReference for the controller.
setFixedSearchResults(fixedSearchResults)It defines a list of fixed search results to be returned by all subsequent SOSL statements in a test method.All subsequent SOSL queries return no results if opt_set_search_results is not specified.
setMock(interfaceType, instance)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.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.
setReadOnlyApplicationMode(applicationMode)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.Do not use setReadOnlyApplicationMode for purposes unrelated to read-only-mode testing such as simulating DML exceptions.
startTest()It marks the point in a test code when the test actually begins. This method is used when the governor limits are being tested.It can be used with stopTest to ensure that all asynchronous calls that come after the startTest method are run before doing any assertions or testing. Each test method is allowed to call this method only once. All of the code before this method should be used to initialize variables, populate data structures, and so on, which allow the set up of everything needed to run the test. Any code that executes after the call to startTest and before the call to stopTest is assigned a new set of governor limits.
stopTest()It marks the point in the test code when the test ends. This method is used with the startTest method.Each test method is allowed to call this method only once. Any code that executes after the stopTest method is assigned the original limits that were in effect before startTest was called. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.
testInstall(installImplementation, version, isPush)It tests the use of the InstallHandler interface, which is used for specifying a post install script in packages. The tests run as the test initiator in the development environment.It throws a run-time exception if the test install fails.
testSandboxPostCopyScript(script, organizationId, sandboxId, sandboxName)It tests the implementation of the *** used for specifying a script to run at the completion of a Sandbox copy. Tests run as the test initiator in the development environment.It throws a run-time exception if the test install fails.    
testUninstall(uninstallImplementation)It tests the implementation of the UninstallHandler interface, which is used for specifying an uninstall script in packages. Tests run as the test initiator in the development environment.It throws a run-time exception if the test uninstall fails.

How to Create 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 will be required to run this code in the developer’s console and then put your custom-designed apex class code to 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.

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!

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 test coverage code. Classes defined with this annotation do not count your organization’s Apex code limits.
  • @testSetup: It indicates the specific method used to set the test data. If @testSetup is specified, then 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 amount of coinciding tests do not apply to those test classes.

Preparing for a Salesforce Admin Interview! Check out our Top Salesforce Admin Interview Questions and Answers.

Best Practices of Test Classes in Salesforce

Some rules to write test classes in Salesforce are:

  • Always start with @is Test annotations to make Salesforce understand that you are writing a test class.
  • Always try to keep the class private, try to name it as the original class or trigger name.
  • Methods of your test class have to be static; 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 properly and give 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, then your test category will fail and will 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 are waiting for each other to roll back data. Such a wait can happen if two tests insert records with the same unique index field values in different orders.

Get 100% Hike!

Master Most in Demand Skills Now !

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 class, Visualforce Controller, Queueable Apex, Future Apex, Visualforce Extensions, and Batch Apex  to know how to create test classes.

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.

Have any more queries regarding Salesforce Developer Jobs, Join our Salesforce Community page and get your queries answered.

Course Schedule

Name Date
Salesforce Certification 2022-10-08 2022-10-09
(Sat-Sun) Weekend batch
View Details
Salesforce Certification 2022-10-15 2022-10-16
(Sat-Sun) Weekend batch
View Details
Salesforce Certification 2022-10-22 2022-10-23
(Sat-Sun) Weekend batch
View Details

Leave a Reply

Your email address will not be published. Required fields are marked *

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.