Intermediate 15 min read

Assertions and Common Patterns

By the end of this lesson, you'll be able to:

  • Use System.assertEquals, assertNotEquals, and assert to verify behavior
  • Follow the arrange-act-assert pattern for readable tests

Prerequisites: Setting Up Test Data

The core assertion methods

System.assertEquals(expected, actual, [message]), System.assertNotEquals(...), and System.assert(condition, [message]) cover almost everything you'll need. Always pass the expected value first and the actual value second — the failure message reads correctly that way. The optional message argument makes a failing test much faster to diagnose.

Arrange, Act, Assert

Structure every test method in three visible phases: arrange (build the data), act (call exactly the thing you're testing), assert (check the outcome). One logical behavior per test method — not a dozen unrelated assertions crammed into a single giant test.

A test in three clear phases

@isTest
static void discountedPriceAppliesTenPercentOff() {
    // Arrange
    Decimal originalPrice = 100;

    // Act
    Decimal result = PricingService.applyDiscount(originalPrice, 0.10);

    // Assert
    System.assertEquals(90, result, 'A 10% discount on 100 should be 90');
}

The three phases stay visually separated even without comments once you get used to the pattern — it's what makes a failing test easy to diagnose at a glance.

Exercise

Write a test asserting that MathHelper.isEven(4) returns true and MathHelper.isEven(3) returns false.

Show hint

Use System.assert() for booleans, negating it for the false case.

APEX

Assertions and Common Patterns — Quick Check

1. In System.assertEquals(expected, actual), which argument comes first?

2. A single test method should ideally verify one specific behavior, not many unrelated ones.

3. What does the 'arrange' phase of a test do?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

System.assertEquals(expected, actual) is the workhorse assertion; structuring every test as arrange (set up data), act (call the code under test), assert (check the result) keeps tests readable and focused on one behavior each.