Hot Posts

6/recent/ticker-posts

Test Class in Salesforce

Test Class in Salesforce

What is a Test Class in Salesforce?

In Salesforce, a test class serves the purpose of testing the functionality of another class, typically an Apex class, trigger, or web service. These test classes are written in Apex and are utilized to ensure that the code developed by developers functions as intended before it is deployed to a production environment.

It is important to note that test classes are not included in code coverage calculations until they are deployed by the Salesforce Admin in the final production stage. Test classes in Salesforce contribute to approximately 75 per cent of code coverage, indicating that a significant portion of the testing process is carried out by these test classes themselves. They operate in a similar manner to Python testing, where the written code is evaluated by a just-in-time compiler that executes the testing process.

Test Methods

1. createStub(parentType, stubProvider) Explanation: This function is used to generate a stubbed version of an Apex class. It can be utilized in conjunction with the System.StubProvider interface to construct a mocking framework. Example: This function is compatible with the System.StubProvider interface. By utilizing the StubProvider interface, it defines the behavior of the stubbed object.

2. enableChangeDataCapture() Explanation: This method is employed in an Apex test to generate change event notifications for all supported Change Data Capture entities. Example: By enabling change data capture, this method ensures that Apex tests can trigger change event triggers.

3. enqueueBatchJobs(numberOfJobs) Explanation: This function adds the specified number of jobs with no-operation contents to the test-context queue. Example: It is utilized to reduce testing time. Instead of using real batch jobs for testing, this function can be used to simulate batch-job enqueuing.

4. getEventBus() Explanation: This function retrieves an instance of the test event bus broker. It allows operations on platform events or change event messages in an Apex test. Example: To perform operations on platform events or change event messages within an Apex test, this function encapsulates Test.getEventBus().deliver() within the Test.startTest() and Test.stopTest() statement block.

5. getFlexQueueOrder() Explanation: This method returns an ordered list of job IDs for jobs in the test-context flex queue.

Example: For testing purposes, this method retrieves the job IDs in the flex queue.

6. getStandardPricebookId() Explanation: This function retrieves the ID of the standard price book in the organization. Example: Regardless of whether the test can query organization data, this function returns the ID of the standard price book.

7. invokeContinuationMethod(controller, request) Explanation: This function activates the callback method for the specified controller and continues in a test method. Example: To test continuations, the Test.setContinuationResponse and Test.invokeContinuationMethod methods are used. Test.setContinuationResponse.

8. The isRunningTest() method is utilized to determine whether the code is being executed within a testing environment. It is commonly used when different code needs to be run depending on whether it was being called from a test.

9. The loadData(sObjectToken, resourceName) method is used to insert test records from a specified static resource .csv file for a specified sObject type. It returns a list of the inserted sObjects. To use this method, a pre-created static resource in CSV format with field names and values for test records is required. The static resource must have the MIME type assigned as text/csv, application/vnd.ms-excel, or application/octet-stream.

10. The newSendEmailQuickActionDefaults(contextId, replyToId) method is employed to create a new QuickAction object that is pre-configured for sending emails. It includes default values for the context and reply-to IDs. This method is useful when there is a need to quickly create a new QuickAction for email sending purposes.

11. To test continuations in Salesforce, the setContinuationResponse(requestLabel, mockResponse) method is used. It allows setting a mock response for a continuation HTTP request in a test method. This method, along with the Test.invokeContinuationMethod, enables the setting of a mock response and executing the associated callback method to process the response during testing.

12. The setCreatedDate(recordId, createdDatetime) method is used to set the CreatedDate for a test-context sObject in Salesforce. It should be called after inserting the test record and should not have a future date to avoid unexpected outcomes. It is important to note that this method cannot be used on pre-existing records, as all database changes are reverted at the end of Salesforce tests.

13. The setCurrentPage(page) method is utilized to set the current PageReference for the controller. This method establishes the controller's current PageReference object, allowing for navigation and interaction with different pages within the controller's context.

14. Assign the provided PageReference object as the current page reference for the controller by using the setCurrentPageReference(page) method.

15. Specify a list of fixed search results to be returned by all subsequent SOSL statements in a test method with the setFixedSearchResults(fixedSearchResults) method. If opt_set_search_results is not specified, all subsequent SOSL queries return no results.

16. Instruct 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 by using the setMock(interfaceType, instance) method. To mock a callout, call Test.setMock from a test method in the same package with the same namespace if the code that performs the callout is in a managed package.

17. Simulate read-only mode during Salesforce upgrades and downtimes by setting the application mode to read-only with the setReadOnlyApplicationMode(applicationMode) method. 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.

18. Mark the point in a test code when the test actually begins by using the startTest() method. This method is used when the governor limits are being tested. 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. Mark the point in the test code when the test ends by using the stopTest() method. This method is used with the startTest method. 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. The function testInstall is utilized to evaluate the functionality of the InstallHandler interface, which is employed to define a post-install script in packages. This function will throw a run-time exception if the test installation is unsuccessful.

21. The purpose of testSandboxPostCopyScript is to verify the execution of the specified script after the completion of a sandbox copy. This function will throw a run-time exception if the test installation fails.

22. The estUninstall function is responsible for testing the implementation of the UninstallHandler interface, which is utilized to specify an uninstall script in packages. If the test uninstallation fails, this function will throw a run-time exception.

How Do We Write a Test Class in Salesforce?

1. To begin, access the Salesforce dashboard.

2. Navigate to the Quick Find tab and search for Apex Classes.

3. Select the option to create a new Apex Class.

4. Within the new class, include the test class definition.

5. Ensure that the syntax follows the specified format.

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

Step 6 – Your code will look somewhat like this depending on the object and trigger you have created in your Salesforce account.

Step 7 – Execute this code in the developer's console and then insert your custom-designed apex class code into the console.

Step 8 – Execute this code to verify the output in the console.

Step 9 – Choose the test class you wish to execute. Step 10 – To include all methods in the test class for the test run, click on Add Selected.

Step 11 – Click on Run.

Step 12 – The test result will be shown in the Tests tab. Optionally, you can expand the test class in the Tests tab to see which methods were executed. In this scenario, the class only contains one test method. Your Test Class has been created.

Benefits of Test Classes in Salesforce

1. Test classes in Salesforce offer several advantages, including the reduction of bug costs by aiding in troubleshooting.

2. By allowing bulk tests to be performed simultaneously, test classes in Salesforce enhance efficiency.

3. Test classes also guarantee the desired output for users, ensuring a seamless experience.

4. Moreover, they contribute to the delivery of high-quality apps to the production organization, ultimately increasing productivity for production users.

Annotations of Test Class in Salesforce

In a Salesforce test class, there are several annotations that can be used to indicate specific functionalities.

The @isTest annotation is used at the class or method level to indicate that it contains only the test coverage code.

On the other hand, @testSetup is used to specify the method used to set the test data, which will be executed before any other method in the test class.

To make test coverage easier, @testVisible annotations can be used on private or protected members to allow access to test classes while maintaining the visibility defined for non-test classes.

Additionally, @isTest(SeeAllData=True) can provide access to existing data in test classes and test methods, but precautions must be taken when using it.

Finally, the @isTest(isParallel=true) annotation can be used to run categories of tests in parallel without being limited by default limits on the number of coinciding tests.

Best Practices for Test Classes in Salesforce

The following are some guidelines for writing test classes in Salesforce: 1. Begin your test class with the @isTest annotation to indicate to Salesforce that you are writing a test class.

2. Keep the class private and try to name it after the original class or trigger.

3. Ensure that the methods in your test class are static and use the void and testMethod keywords.

4. Utilize Test.startTest() and Test.stopTest() to ensure that the actual testing of the code is performed with a new set of governor constraints. These methods help reset the governor limits before executing the test code.

5. Between Test.startTest() and Test.stopTest(), use assert statements to verify whether your actual code is executed as expected and produces the desired results.

6. In your specific case, you are testing whether the book's worth has been set to 90 or not. If the assert statement returns false, it means that the test has failed, indicating that there is an issue in your code that needs to be fixed. When running tests in parallel, deadlocks can occur when multiple tests attempt to create records with duplicate index field values. A deadlock happens when two tests wait for each other to roll back their data. This situation can arise if two tests insert records with the same unique index field values in different orders.

In conclusion, it is crucial for individuals aiming to test the logic for various components in Salesforce, such as Apex triggers, Apex classes, Visualforce Controllers, Queueable Apex, Future Apex, Visualforce Extensions, and Batch Apex, to have a thorough understanding of creating test classes. This blog aims to provide you with insights into the utilization of test classes in Salesforce, including the implementation of different test methods.

Post a Comment

0 Comments