Salesforce Apex Test Class Best Practices
If you’re planning to get a job as a Salesforce developer one day, these testing principles are an absolute must learn!
To get the minimum required 75% test coverage, all you have to do is make Salesforce run the code that you want to test.
- Do not put (seeAllData = true) in test class otherwise, use it for exceptional cases.
- Use @isTest at the Top for all the test classes.
- Test in bulk: Test to see if your code can run on 200 records at once. This is the maximum number of records that can be evaluated in a single trigger by Salesforce.Don’t worry about this one too much for now, since we’ll be talking more about it in our Governor Limits chapter! It’s possible that your code runs fine if a single Contact goes through your trigger – but it might break if 200 Contacts are evaluated in your trigger!
- Avoid Using Hard Coding Ids anywhere in test Class or any apex class.
- Use System.runAs() method to test the functionality in user Context.you can use the following line of code for it:_________________________________________________________Profile p = [select id from Profile where Name = ‘System Administrator’ LIMIT 1];
UserRole r = [Select id from UserRole where name = ‘CEO’];
User newUser = new User(FirstName=’Manpreet’, LastName=’Singh’, UserName=’singh2050′, Email=’[email protected]’, Alias=’tester11′, LocaleSidKey=’en_US’, LanguageLocaleKey=’en_US’, EmailEncodingKey=’ISO-8859-1′, CommunityNickname=’singh2050.test’, ProfileId = p.Id, TimeZoneSidKey=’America/New_York’, isActive = true, UserRoleId = r.Id );
- Make sure right tick must appear when you run your test class.Else check for errors.
- Use System.assertEquals() to see if your code has the expected outcomes: for example, if your code changes a Contact’s education to ‘Graduate’, make sure it actually did by doing System.assertEquals(‘Graduate’, myContact.education__c);
- Use Test.startTest() and Test.stopTest() statement to increase Governor Limits of your test code.