Cover an existing Apex class with a unit test that creates fixture data, calls the method under test, and asserts the expected outcome.
- Create the test class
In Setup, Apex Classes, click New. Add the @isTest annotation at the class level. Name the class with a clear suffix (AccountServiceTest).
- Add a @testSetup method
Add a static method annotated @testSetup that inserts the fixture data needed by every test in the class (a few Accounts, a Contact, a User). This runs once per class and resets between methods.
- Write a test method
Add a static method annotated @isTest. Inside, query the fixture data, call the production method, and capture the returned value. The method body should read like a small story: arrange, act, assert.
- Assert the expected outcome
Use Assert.areEqual(expected, actual) or System.assertEquals to compare what happened to what should have happened. Add multiple assertions per test where multiple field updates or related-record creations matter.
- Run the test
From the Developer Console or VS Code, run the test class. Inspect the log if anything fails. Iterate until the test passes consistently.
- Verify coverage
Open the Apex Test Execution result. Confirm the target class shows expected coverage. If branches are uncovered, add additional test methods for the missing cases.
- Tests cannot make real HTTP callouts. Every callout in production code needs an HttpCalloutMock implementation; the test fails with CalloutException otherwise.
- @isTest(SeeAllData=true) breaks test isolation and is an anti-pattern. Avoid it unless you are writing a Knowledge or Email Template test that genuinely requires production-only data.
- Parallel test execution exposes data collisions. Tests that modify shared resources (custom settings, queues) need explicit @isTest(IsParallel=false) or careful design.
- Assertions without messages are hard to debug. Pass the third argument to Assert.areEqual to include a helpful failure message; the diagnosis is much faster.