This is Seema Dhingra's presentation on the importance and significance of Test Classes at Dreamforce Global Gathering 2017 organised by New Delhi Salesforce Developer Group and Gurgaon WIT at Nagarro Gurgaon Campus.
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 are not 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 Syntax and 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