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.

dont miss out iconDon't forget to check out: What is The Use of Test Class in Salesforce | Developer Guide

    1. Do not put (seeAllData = true) in test class otherwise, use it for exceptional cases.
      Salesforce apex
    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!
      apex test class
    4. Avoid Using Hard Coding Ids anywhere in test Class or any Salesforrce apex class.
    5. 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 );
      insert newUser;
      System.runAs(newUser) {
      //
      }
    6. Make sure right tick must appear when you run your test class. Else check for errors.
      test class in salesforce

dont miss out iconLearn more about: What is Wrapper Class in Salesforce

  1. 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);
  2. Use Test.startTest() and Test.stopTest() statement to increase Governor Limits of your test code.
    test class best practices
    Cheers!!!
    salesforce apex test

Popular Salesforce Blogs