Salesforce Developer – Test Classes Questions
Test classes are fundamental to Salesforce development, ensuring code quality, maintaining coverage requirements, and enabling safe deployments. These questions cover test class structure, mocking techniques, assertion strategies, and best practices for comprehensive testing. Understanding how to write effective tests is essential for any Salesforce Developer looking to build reliable and maintainable applications.
Test Classes - Q&A
- Q1. What are the key requirements for test classes in Salesforce?
Ans: Core requirements: - Minimum 75% code coverage (org-wide) - Test all code paths (positive/negative) - Use @isTest annotation - No DML in class declaration - Test data isolation (no seeAllData=true unless necessary) - Assert expected outcomes - Test governor limit handling - Q2. Explain the Test.startTest() and Test.stopTest() methods.
Ans: Test boundary markers: - Test.startTest(): * Resets governor limits * Marks beginning of tested code * Enables async execution in tests - Test.stopTest(): * Forces async job execution * Marks end of tested code * Restores original limits context Example:@isTest private class MyTestClass { @isTest static void testMethod() { Test.startTest(); // Code under test MyClass.myMethod(); Test.stopTest(); // Verify results } }
- Q3. What are the different ways to create test data?
Ans: Test data approaches: - Direct DML: insert new Account(Name='Test'); - @testSetup: Shared data across methods - Test.loadData(): Static resource CSV - TestFactory pattern: Reusable data creation - Mocking: HttpCalloutMock, StubProvider Best practice: Create only necessary data - Q4. How do you mock HTTP callouts in test classes?
Ans: HttpCalloutMock implementation:@isTest private class MockHttpResponse implements HttpCalloutMock { public HttpResponse respond(HttpRequest request) { HttpResponse response = new HttpResponse(); response.setStatusCode(200); response.setBody('{"status":"success"}'); return response; } } // In test method: Test.setMock(HttpCalloutMock.class, new MockHttpResponse()); Test.startTest(); // Code that makes callout Test.stopTest();
- Q5. What is the purpose of @testSetup and when should you use it?
Ans: @testSetup benefits: - Reduces redundant data creation - Improves test performance - Ensures data consistency - Shared across test methods Example:@testSetup static void setupTestData() { Account testAcc = new Account(Name='Test Account'); insert testAcc; // Other shared data }
Use when multiple methods need same base data - Q6. How do you handle test data isolation and seeAllData parameter?
Ans: Data isolation principles: - Default: seeAllData=false (recommended) - Test data doesn't persist in org - Cannot access production records - Exception: seeAllData=true for: * Legacy orgs * Certain setup objects * External ID matching Best practice: Always use isolated test data - Q7. What are the best practices for assertion strategies?
Ans: Assertion guidelines: - Use System.assert methods - Test both positive and negative cases - Assert specific values, not just existence - Use meaningful assertion messages - Verify all expected outcomes Example:System.assertEquals( 'Expected Value', actualValue, 'Field should match expected value' );
- Q8. How do you test exception handling in Apex?
Ans: Exception testing pattern:@isTest static void testExceptionHandling() { try { MyClass.processData(null); // Should throw exception System.assert(false, 'Expected exception not thrown'); } catch (MyCustomException e) { System.assertEquals( 'Invalid input', e.getMessage() ); } }
Test both expected and unexpected exceptions - Q9. What are the governor limit considerations in testing?
Ans: Limit management: - Test.startTest() resets limits - Monitor heap size, SOQL, DML counts - Test bulk operations (200+ records) - Verify async job limits - Check CPU time consumption Use Limits methods for monitoring:Integer queriesUsed = Limits.getQueries(); System.assert(queriesUsed < 5, 'Too many queries');
- Q10. How do you implement test factories for reusable data creation?
Ans: Factory pattern:public class TestDataFactory { public static Account createAccount(String name) { Account acc = new Account( Name = name, Type = 'Customer' ); insert acc; return acc; } public static List
createContacts( Integer count, Id accountId ) { List contacts = new List (); for (Integer i = 0; i < count; i++) { contacts.add(new Contact( LastName = 'Test ' + i, AccountId = accountId )); } insert contacts; return contacts; } } - Q11. What are the security considerations for test classes?
Ans: Security aspects: - Test with various user profiles - Verify CRUD/FLS enforcement - Test sharing rule impacts - Validate field-level security - Check for data exposure Example:User testUser = [SELECT Id FROM User WHERE Profile.Name='Standard User' LIMIT 1]; System.runAs(testUser) { // Test with restricted user }
- Q12. How do you test asynchronous code (Batch, Queueable, Future)?
Ans: Async testing approach:@isTest static void testBatchJob() { // Setup test data Test.startTest(); // Execute batch MyBatch batchJob = new MyBatch(); ID jobId = Database.executeBatch(batchJob); Test.stopTest(); // Verify results AsyncApexJob job = [SELECT Status FROM AsyncApexJob WHERE Id = :jobId]; System.assertEquals('Completed', job.Status); }
- Q13. What are common test class anti-patterns?
Ans: Avoid these practices: - Hardcoding IDs or usernames - Testing implementation details - Ignoring negative test cases - Over-mocking external systems - Creating unnecessary test data - Asserting without meaningful messages - Using seeAllData=true unnecessarily - Q14. How do you measure and improve test coverage effectively?
Ans: Coverage strategies: - Aim for 100% coverage (not just 75%) - Test all code paths - Use Developer Console coverage view - Run all tests to check overall coverage - Focus on quality over quantity - Refactor untestable code - Use code coverage tools - Q15. Explain real-world test class scenarios.
Ans: Practical applications: - Trigger handler testing - Web service integration testing - Complex business logic validation - Security and sharing verification - Performance boundary testing - Error handling validation - Multi-user scenario testing - Integration point validation