Advanced 25 min read

Your First Test Class

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

  • Write a complete, runnable test class with the correct naming and annotation conventions
  • Explain the private class / static method convention
  • Run a test class and read its result

Prerequisites: "Why Tests Matter"

The standard shape

@isTest
private class CalculatorTest {
    @isTest
    static void calculateAndFormatHandlesAddition() {
        Calculator calc = new Calculator();
        String result = calc.calculateAndFormat(12, 5, '+');
        System.assertEquals('12 + 5 = 17.00', result);
    }
}
  • @isTest on the class marks the whole class as test-only.
  • private class is the conventional (and typically required) access level for a test class.
  • @isTest on the method, plus static void, marks an individual test method — every test method must be static, since it doesn't operate on any instance of the test class itself.
  • TestClassName matching ClassNameTest (here, CalculatorTest testing Calculator) is a strong, widely-followed naming convention, not a compiler requirement.

One test method, one scenario

@isTest
private class CalculatorTest {
    @isTest
    static void additionReturnsCorrectSum() {
        Calculator calc = new Calculator();
        System.assertEquals('12 + 5 = 17.00', calc.calculateAndFormat(12, 5, '+'));
    }

    @isTest
    static void divisionByZeroReturnsErrorMessage() {
        Calculator calc = new Calculator();
        System.assertEquals('Error: cannot divide by zero.', calc.calculateAndFormat(10, 0, '/'));
    }
}

Each @isTest static void method verifies exactly one scenario — this mirrors Module 26's "Design the Requirement" habit of naming each edge case explicitly, now with one dedicated test method per case instead of one long manual script trying to cover everything.

Running the test and reading the result

Running CalculatorTest (via the Developer Console, VS Code, or CI) reports each test method as pass or fail individually — additionReturnsCorrectSum passing and divisionByZeroReturnsErrorMessage failing tells you exactly which scenario broke, immediately, rather than needing to guess from one long manual script.

Exercise

Write a complete test class BookTest with one test method verifying that a Book's summary() method (from Module 12) returns the expected string.

Show hint

Follow the @isTest / private class / static void structure exactly.

APEX

Your First Test Class Quiz

1. Why must every test method be static?

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

This lesson writes a real, complete test class from scratch for the Calculator class from Module 8 — the conventions, structure, and exact syntax every subsequent lesson builds on.