Testing Apex
What is Test class in salesforce?
What Components needs to be tested?
Syntax of basic test class and test method Test class best practices
2. Agenda
❖ What is Test class in salesforce?
❖ What Components needs to be test?
❖ Syntax of basic test class and test method
❖ Test class best practices
3. What is test class in Salesforce
❖ A test class in Salesforce is also an Apex Class which is used to test the logic for Apex
trigger, Apex Class, VF Controller, VF Extensions, Batch Apex, Queueable Apex, future
apex.
❖ Test class insures that every logic is working as expected in both Positive & Negative
Testing.
❖ Test class code does not count in overall code coverage.
❖ Every Apex Class must have at least 75% code coverage before deploying into production
environment.
❖ Every Apex Trigger must need to have at least 1% code coverage.
❖ VF, VF Component, Lightning Component does not require any test class to migrate to
Production Environment.
!3
4. What component needs to be tested
❖ Apex Trigger
❖ Apex Class
❖ Batch Apex
❖ VF Controller/Extensions
❖ Future/Queueable Apex
❖ Restricted User
5. Write Basic Apex Test class
@isTest
private class MyTestClass {
@isTest static void myTest() {
// code_block
}
}
6. Test Class Best Practices
1. Use @isTest at the Top for all the test classes
2. Always put assert statements for negative and positive tests
3. Use the @testSetup method to insert the test data into Test class that will flow data all over the test class.
4. Use Utility Class to prepare the test data if same data is used in multiple test classes.
5. Always use Test.startTest() and Test.stopTest() doing this it will increase the governor limit of salesforce. We also
use this to increase the governor limit.
6. Use System.runAs() method to test the functionality in user Context.
7. Do not put (seeAllData = true) in test class otherwise, use it for exceptional cases.
8. Avoid Using Hard Coding Ids anywhere in test Class or any apex class.
9. Please make sure that each class has minimum 75% coverage and also the main functionality has been covered.
10. All class method must be tested in bulk way (for at least 200 records) and keep the real scenarios in mind.
11. Only one Test.startTest() and Test.stopTest() statement can be in a method, and no of Test.startTest() and
Test.stopTest() statement in any test class depend upon the test methods.