Preface – This post is part of the Write Your First Intermediate Trigger series.
To get the minimum required 75% test coverage, all you have to do is make Salesforce run the code that you want to test. So if you have a “before insert” trigger on Contacts, simply creating a new Contact in your test class will get you your code coverage!
In the beginning, it might seem sufficient just to get enough code coverage to deploy your code. Experienced developers however will always take a few extra steps to also make sure their code is rock solid too.
If you’re planning to get a job as a Salesforce developer one day, these testing principles are an absolute must learn!
Salesforce Apex Testing Best Practices:
1. Create all records in your test from scratch: Assume you’ll be deploying your code in an org that has no records!
Why? If any records in your production org get deleted or changed, there’s no chance your test class fails since it builds its own records!
Best Practice #1: Create records from scratch!
2. Use System.assertEquals() to see if your code has the expected outcomes: for example, if your code changes a Contact’s status to ‘Single’, make sure it actually did by doing System.assertEquals(‘Single’, myContact.Status__c);
Why? Just because you get full code coverage, doesn’t mean your code actually works!
Best Practice #2: Be “assert”-ive!
3. Test for scenarios that shouldn’t work: Let’s say in our previous example that we changed our Contact’s status to ‘Single’ only if he lost his job as a Salesforce developer. We’d also want to test this scenario using System.assertEquals(‘In a Relationship’, myContact.Status__c);
Why? This tests to see if our code does things it shouldn’t do! This is called negative testing, and it makes sure we evaluate our code 360 degrees.
Best Practice #3: Break things!
4. 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!
Best Practice #4: Be “bulky”
That’s almost 200 pounds, just like the maximum batch size in Salesforce!
We’ll apply these principles (with specific examples) when we create the test class for our deduping trigger!
Next post: We write a test class for our deduping trigger!