Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 36 ยท Classes and Testing

Apex Test Classes, Assertions and Code Coverage

Write Apex unit tests: @isTest, System.Assert methods, Test.startTest and stopTest, bulk and negative tests, and the 75 percent coverage rule, with a Java test-harness stand-in.

Salesforce will not let you deploy Apex to production unless at least 75 percent of your Apex lines are covered by tests, and every trigger needs some coverage. But coverage is the minimum, not the goal. A good test proves behaviour: it sets up data, runs your code, and asserts what changed. This lesson shows how Apex tests are structured and how to write assertions that catch real bugs.

Apex tests run only in an org (or scratch org). On this site the Apex listings are read-only and shown without output. The runnable examples are Java stand-ins that mimic a tiny test harness, so you can practise the arrange-act-assert shape.

Anatomy of a test class

A test class is annotated @isTest. Its methods are static testMethod-style or, more commonly, annotated @isTest as well. Test classes do not count against your org's code size limit.

APEX
public with sharing class DiscountCalculator {
    public static Decimal apply(Decimal price, Integer quantity) {
        if (price == null || price < 0) {
            throw new IllegalArgumentException('price must be zero or more');
        }
        return quantity >= 100 ? price * 0.90 : price;
    }
}
APEX
@isTest
private class DiscountCalculatorTest {

    @isTest
    static void smallOrdersGetNoDiscount() {
        Decimal result = DiscountCalculator.apply(200, 5);
        Assert.areEqual(200, result, 'No discount below 100 units');
    }

    @isTest
    static void largeOrdersGetTenPercentOff() {
        Decimal result = DiscountCalculator.apply(200, 100);
        Assert.areEqual(180, result, '10 percent off at 100 units');
    }

    @isTest
    static void negativePriceIsRejected() {
        try {
            DiscountCalculator.apply(-1, 1);
            Assert.fail('Expected an exception');
        } catch (IllegalArgumentException e) {
            Assert.isTrue(e.getMessage().contains('zero or more'));
        }
    }
}

Assert is the modern assertion class: Assert.areEqual(expected, actual, message), Assert.areNotEqual, Assert.isTrue, Assert.isFalse, Assert.isNull, Assert.isNotNull, Assert.fail and Assert.isInstanceOfType. Older code uses System.assertEquals and System.assert; both work. Always pass a message: it appears in the failure output.

Tests own their data

Apex tests do not see your org's real data by default (unless you add @isTest(SeeAllData=true), which you should almost never do). Each test method creates the records it needs, and all changes are rolled back when the method ends.

APEX
@isTest
static void insertingAccountSetsDefaultRating() {
    Account a = new Account(Name = 'Test Co');
    insert a;

    Account saved = [SELECT Rating FROM Account WHERE Id = :a.Id];
    Assert.areEqual('Warm', saved.Rating);
}

Reuse data by writing a @TestSetup method; it runs once per class and every test method gets a fresh copy of what it created. We cover factories and mocks in test data and mocking.

startTest and stopTest

Test.startTest() and Test.stopTest() bracket the code under test. Two reasons they matter: governor limits are reset at startTest, so your setup does not consume the limits of the code you are testing, and stopTest forces any asynchronous work (future, queueable, batch) started in between to run to completion, so you can assert on its effects.

APEX
@isTest
static void queueableUpdatesAccounts() {
    Account a = new Account(Name = 'Async Co');
    insert a;

    Test.startTest();
    System.enqueueJob(new RatingJob(new List<Id>{ a.Id }));
    Test.stopTest();

    Assert.areEqual('Hot', [SELECT Rating FROM Account WHERE Id = :a.Id].Rating);
}

(RatingJob is built in the Queueable lesson.)

What to test

  1. The happy path: one record, normal input.
  2. Bulk: insert 200 records, because triggers and batches receive up to 200 at a time. A bug that only appears with many rows (a SOQL query inside a loop) shows up here.
  3. Negative cases: bad input, missing required values, and the errors you expect.
  4. Permissions: use System.runAs(user) to run as a user with a particular profile and check sharing or field security behaves.

Try the idea: arrange, act, assert (Java stand-in)

Java Stand-in: a tiny test harness (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The third test fails on purpose so you can see the shape of a failure message. In Apex the test runner prints similar text: the assertion message plus expected and actual values.

Try the idea: bulk test (Java stand-in)

Java Stand-in: why bulk tests matter (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A single-record test passes both versions; a 200-record test exposes the first one, which would breach Apex's limit of 100 SOQL queries.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Test.stopTest() do for asynchronous Apex started after startTest()?

    stopTest runs the queued future, queueable and batch work synchronously before returning, so assertions can see the effects.
  2. 2. How much Apex code coverage must a production deployment have overall?

    At least 75 percent of Apex lines must be covered and all tests must pass; each trigger also needs some coverage.
  3. 3. Why should you test with 200 records, not just one?

    Bulk tests reveal queries or DML inside loops that would hit governor limits.
  4. 4. Which is the best default for test data?

    Tests should create their own data so they are repeatable in any org; SeeAllData makes tests depend on whatever the org contains.

Summary

  • Test classes use @isTest; methods assert with Assert.areEqual and friends.
  • Tests create their own data and are rolled back automatically.
  • Test.startTest() and stopTest() reset limits and flush async work.
  • Test the happy path, bulk, negative cases and permissions; 75 percent coverage is the floor, not the goal.

Next: Test Data Factories and Mocking