Salesforce Dictionary - Free Salesforce GlossarySalesforce Dictionary
Full Unit Test entry
How-to guide

Write a unit test for an Apex class

Cover an existing Apex class with a unit test that creates fixture data, calls the method under test, and asserts the expected outcome.

By Dipojjal Chakrabarti · Founder & Editor, Salesforce DictionaryLast updated May 26, 2026

Cover an existing Apex class with a unit test that creates fixture data, calls the method under test, and asserts the expected outcome.

  1. 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).

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

Gotchas
  • 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.

See the full Unit Test entry

Unit Test includes the definition, worked example, deep dive, related terms, and a quiz.