Salesforce Testing & Debugging
Master the art of writing robust test classes, debugging complex issues, and ensuring code coverage in Salesforce. Learn industry best practices for testing and debugging Apex code effectively.
Start Testing MasteryWhy Testing & Debugging Matters in Salesforce
Testing and debugging are critical components of Salesforce development. With Salesforce’s requirement of 75% code coverage for deployment to production, mastering testing techniques is essential for every developer.
Apex Test Classes
Learn to create comprehensive test classes that validate your Apex code functionality and ensure it meets Salesforce’s deployment requirements.
Debugging Techniques
Master debugging tools like Debug Logs, System.debug(), and the Developer Console to identify and fix issues in your Salesforce applications.
Code Coverage
Understand how to measure and improve code coverage to meet Salesforce’s 75% minimum requirement and ensure robust, error-free code.
Apex Test Class Examples
Writing effective test classes is crucial for Salesforce development. Below are examples of properly structured test classes.
Basic Test Class Structure
@isTest
private class TestAccountProcessor {
@isTest
static void testUpdateAccountDescription() {
// Create test data
Account testAccount = new Account(
Name = 'Test Account',
NumberOfEmployees = 50
);
insert testAccount;
// Start test context
Test.startTest();
// Call the method to test
List<Id> accountIds = new List<Id>{testAccount.Id};
AccountProcessor.updateAccountDescription(accountIds);
Test.stopTest();
// Verify results
Account updatedAccount = [SELECT Description FROM Account WHERE Id = :testAccount.Id];
System.assert(updatedAccount.Description.contains('Test Account'),
'Account description should contain account name');
System.assert(updatedAccount.Description.contains('50'),
'Account description should contain employee count');
}
@isTest
static void testBulkAccountProcessing() {
// Create bulk test data (200 accounts)
List<Account> accounts = new List<Account>();
for(Integer i = 0; i < 200; i++) {
accounts.add(new Account(
Name = 'Test Account ' + i,
NumberOfEmployees = i
));
}
insert accounts;
// Prepare account IDs
List<Id> accountIds = new List<Id>();
for(Account acc : accounts) {
accountIds.add(acc.Id);
}
Test.startTest();
AccountProcessor.updateAccountDescription(accountIds);
Test.stopTest();
// Verify all accounts were updated
List<Account> updatedAccounts = [SELECT Description FROM Account WHERE Id IN :accountIds];
System.assertEquals(200, updatedAccounts.size(), 'All 200 accounts should be updated');
}
}
Test Class with Mocking
@isTest
global class TestHttpCalloutMock implements HttpCalloutMock {
global HTTPResponse respond(HTTPRequest req) {
// Create a fake response
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"status":"success","data":{"id":"12345","name":"Test Response"}}');
res.setStatusCode(200);
return res;
}
}
@isTest
private class TestExternalServiceCaller {
@isTest
static void testCallExternalService() {
// Set mock callout class
Test.setMock(HttpCalloutMock.class, new TestHttpCalloutMock());
Test.startTest();
HttpResponse result = ExternalServiceCaller.makeCallout();
Test.stopTest();
// Verify the response was processed correctly
System.assertEquals(200, result.getStatusCode(), 'Status code should be 200');
System.assert(result.getBody().contains('success'), 'Response should contain success status');
}
}
Interactive Debugging Simulator
Practice debugging with this interactive simulator. Click the debug buttons to see different types of debug outputs.
Debug Log Simulator
Debugging Best Practices:
- Use System.debug() strategically – don’t overuse it in production code
- Organize debug logs with labels like [DEBUG], [ERROR], [INFO]
- Use different logging levels (FINE, FINER, FINEST) for detailed tracing
- Always clean up debug statements before deploying to production
Code Coverage Calculator
Calculate your test coverage percentage and see if you meet Salesforce’s 75% requirement.
Code Coverage Result
Tips to Improve Code Coverage:
- Write test methods for all positive and negative scenarios
- Test bulk operations (200+ records)
- Test with different user profiles using runAs() method
- Use Test.startTest() and Test.stopTest() to reset governor limits
- Test all branches of conditional statements (if/else, switch)
Testing Checklist
Use this checklist to ensure your test classes are comprehensive and effective.
Test Data Setup
Create all necessary test data using @testSetup or within test methods.
Test Negative Scenarios
Test error handling, exceptions, and invalid inputs.
Bulk Testing
Test with 200+ records to ensure bulkification works correctly.
Governor Limits
Test that code respects governor limits and handles limit exceptions.
Assertions
Include System.assert() statements to verify expected outcomes.
Mastering Salesforce Testing & Debugging
Effective testing and debugging are essential skills for any Salesforce developer. With Salesforce’s strict deployment requirements and complex business logic, understanding how to properly test and debug Apex code can save countless hours and prevent production issues.
Why Comprehensive Testing is Critical:
- Deployment Requirements: Salesforce requires 75% code coverage for deployment to production
- Quality Assurance: Thorough testing ensures your code works as expected in all scenarios
- Regulatory Compliance: Many industries require extensive testing for compliance
- Cost Reduction: Finding bugs early in development is far less expensive than fixing them in production
- User Experience: Well-tested code provides a better, more reliable user experience
Advanced Debugging Techniques:
- Debug Logs: Learn to configure and interpret debug logs with different logging levels
- Developer Console: Use the built-in debugging tools in the Developer Console
- Checkpoints: Set checkpoints to examine variable states at specific execution points
- Anonymous Apex: Execute anonymous Apex for quick testing and debugging
- Test Execution: Run specific test methods to isolate and debug failing tests
Testing Frameworks and Tools:
Beyond standard Apex test classes, Salesforce developers should be familiar with:
- ApexMocks: Framework for implementing mock objects in Apex <
- SOQL Query Testing: Techniques for testing SOQL queries and their results
- Trigger Testing: Best practices for testing Apex triggers with various scenarios
- Performance Testing: Testing code performance and governor limit usage
- Integration Testing: Testing callouts and integrations with external systems
At eLearning Salesforce, our Testing & Debugging course provides hands-on experience with real-world scenarios, from basic test class creation to advanced debugging techniques. You’ll learn not just how to meet the 75% coverage requirement, but how to write meaningful tests that actually validate your business logic.
