Salesforce Apex Test Class Best Practices

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.

  1. Do not put (seeAllData = true) in test class otherwise, use it for exceptional cases.


  2. Use @isTest at the Top for all the test classes.
  3. 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!


  4. Avoid Using Hard Coding Ids anywhere in test Class or any apex class.
  5. Use System.runAs() method to test the functionality in user 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 );

    insert newUser;




  6. Make sure right tick must appear when you run your test class.Else check for errors.


  7. 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);
  8. Use Test.startTest() and Test.stopTest() statement to increase Governor Limits of your test code.




Leave a Reply


We're not around right now. But you can send us an email and we'll get back to you, asap.


About Us

Forcetalks is a Salesforce collaboration platform for coders & developers, geeks & nerds, consultants & business heads, admins & architects, managers & marketers and of course the business owners. A community where you can learn from, where you can contribute to. For you. For Salesforce. Read More...

Copyright 2020 Forcetalks. All Right Reserved.

Log in with your credentials


Forgot your details?