The document details the importance of test classes in Salesforce, emphasizing the need for at least 75% code coverage for deployment and encouraging striving for 100% coverage. It outlines how code coverage is calculated and provides various guidelines for writing effective test methods, including specific annotations and methods to use. Additionally, it mentions considerations like what counts towards code coverage and how to manage data and user contexts in tests.
Test Classes -Salesforce
LEARN . SHARE . CELEBRATE . SALESFORCE
2.
Why Test Classes
•Error-free code
• Check whether code is working as expected or not
• Deploy Apex to a production environment
• Salesforce requires at least 75% of your code to be covered by
our test classes
• Cover each positive and negative use case of your code
3.
Code Coverage Calculation
•Code coverage is calculated by dividing the number of unique
Apex code lines executed during your test method execution by
the total number of Apex code lines in all of your trigger and
classes.
(Note: these numbers do not include lines of code within your
testMethods)
4.
Considerations
• System.debug arenot part of Apex code coverage.
• Test methods and test classes are not counted as part of Apex
code limit.
• Every trigger you are trying to deploy should have at least 1%
coverage
• Class can be deployed on 0% coverage but yes overall coverage
of your production org after getting your code deployed should be
75%, otherwise Salesforce won’t let you deploy your code.
• Strive for 100% code coverage. Do not focus on the 75%
requirement.
• Test methods do not expect any Id or rely upon a specific data
set. Test method will fail when deploy to other organisation.
• System.assertEquals
5.
Test Method Syntaxand Static Methods
• Static testMethod keyword
• @IsTest : Define classes that only contain code used for testing your
application
• Test.isRunningTest() : Returns true if the currently executing code was called
by code contained in a test method, false otherwise
• Test.startTest : Test actually begins. Initialize variables, setup data before it.
Get a fresh set of governor limits for the remainder of the test until you call
Test.stopTest
• System.RunAs : Change user contexts to either an existing user or a new user.
All of that user's record sharing is then enforced
• isTest(SeeAllData = true) : Use on class methods in exceptional cases where
there are sObjects that doesn't allow DML operation e.g. PriceBook creation