- Forcecode Newsletter
- Posts
- How to Write Apex Test Classes That Actually Prove Your Code Works
How to Write Apex Test Classes That Actually Prove Your Code Works
Hey ,
Here's something most Salesforce developers find out the hard way.
Getting to 75% test coverage and having tests that actually work are not the same thing. Coverage tells you which lines were executed during a test run. It doesn't tell you whether those lines did the right thing.
A test class with no assertions will pass every time. It will also catch zero bugs.
Here's what a test class that actually means something looks like.
Name your test methods like documentation. Use meaningful names that tell you exactly what the test is proving. When it fails in a deployment you know immediately what broke and why.
Assert the specific thing you're trying to prove. Use System.assertEquals(expected, actual, message) with a clear failure message. If you're asserting a boolean with no message you're making future debugging much harder than it needs to be.
Always use Test.startTest() and Test.stopTest(). Code before startTest doesn't eat into your governor limits during the actual test. And stopTest forces async operations to complete before your assertions run. If you're testing a Queueable or a future method without it, your assertions are running before the code finishes.
Test three scenarios for every method. The happy path, an edge case like a null value or zero records, and a bulk case with 200 records. If your trigger works on one record but breaks on 200 it will break in production. Test it before it gets there.
Use @TestSetup for shared data. If multiple test methods need the same records, create them once in a @TestSetupmethod. Each test method gets its own copy in its own transaction. It keeps the class clean and avoids the copy-paste setup that makes test classes hard to maintain.
Know the flags interviewers watch for. @isTest(SeeAllData=true) is one of them. It lets your test see real org data which sounds useful but makes tests fragile and environment-dependent. Almost every experienced developer will tell you to avoid it and interviewers know to ask about it.
Don't forget callout mocks. If your code makes an HTTP callout, your test will fail without one. Implement HttpCalloutMock and use Test.setMock(). It's a few extra lines and the only way to properly test code that hits an external API.
We put the full post on the Forcecode blog with code examples for every pattern covered here.
Good luck out there.
The Forcecode Team