Testing
Test Class Patterns
Salesforce requires 75% code coverage for production deployment. Aim for meaningful tests, not line-filling.
AccountServiceTest.cls — Production Pattern
Apex
@IsTest private class AccountServiceTest { @TestSetup // Runs once; data is rolled back between tests static void setupData() { List<Account> accounts = new List<Account>(); for (Integer i = 0; i < 200; i++) { // Always test bulk (200) accounts.add(new Account( Name = 'Test Account ' + i, AnnualRevenue = i * 10000 )); } insert accounts; } @IsTest static void testEnrichAccounts_Positive() { List<Account> accounts = [ SELECT Id, Name, AnnualRevenue FROM Account WHERE Name LIKE 'Test Account%' ]; Test.startTest(); // Resets governor limits AccountService.enrichAccounts(accounts); Test.stopTest(); // Forces async code to complete List<Account> updated = [ SELECT Id, Rating FROM Account WHERE Id IN :accounts AND AnnualRevenue > 1000000 ]; for (Account acc : updated) { System.assertEquals('Hot', acc.Rating, 'High revenue accounts should be Hot'); } } @IsTest static void testEnrichAccounts_EmptyList() { Test.startTest(); try { AccountService.enrichAccounts(new List<Account>()); System.assert(true, 'Should handle empty list gracefully'); } catch (Exception e) { System.assert(false, 'Should not throw on empty list: ' + e.getMessage()); } Test.stopTest(); } @IsTest static void testBatch_EndToEnd() { Test.startTest(); Database.BatchableContext bc; Id batchId = Database.executeBatch(new AccountBatch(), 200); Test.stopTest(); // Batch runs synchronously in test context // Verify batch processed correctly Integer hotCount = [ SELECT COUNT() FROM Account WHERE Rating = 'Hot' AND AnnualRevenue > 1000000 ]; System.assertNotEquals(0, hotCount, 'Should have Hot accounts'); } }