Sub topic 4
Anatomy of a Test Class and Test Method
This chapter assumes you can read basic Apex (classes, static methods, exceptions) and that you know Salesforce requires test coverage before a production deployment. Here you will learn the structure every Apex test shares: the class, the method, the three-phase pattern inside the method, and the rules the platform enforces on both. Later chapters cover assertions, test data, Test.startTest and mocking in more depth.
The class under test
The examples use one small class. It has a happy path and two validation branches.
public with sharing class DiscountCalculator {
public static Decimal apply(Decimal amount, Decimal percent) {
if (amount == null || percent == null) {
throw new IllegalArgumentException('amount and percent are required');
}
if (percent < 0 || percent > 100) {
throw new IllegalArgumentException('percent must be between 0 and 100');
}
return amount - (amount * percent / 100);
}
}A minimal test class
A test class is an ordinary Apex class marked with the @isTest annotation. Its methods are marked with @isTest too.
@isTest
private class DiscountCalculatorTest {
@isTest
static void appliesPercentageDiscount() {
Decimal result = DiscountCalculator.apply(100, 10);
Assert.areEqual(90.00, result, 'A 10% discount on 100 should give 90');
}
@isTest
static void rejectsPercentOutOfRange() {
try {
DiscountCalculator.apply(100, 150);
Assert.fail('Expected an IllegalArgumentException');
} catch (IllegalArgumentException e) {
Assert.isTrue(e.getMessage().contains('between 0 and 100'), 'Unexpected message: ' + e.getMessage());
}
}
}Each part of this class has a job.
| Part | Rule or purpose |
|---|---|
| `@isTest` on the class | Tells the platform this class holds tests. Its code is excluded from the org's Apex code size limit and from coverage calculations. |
| `private` | Test classes are usually private. The test runner can still execute them. |
| `@isTest` on a method | Marks the method as a test. The platform runs only methods carrying this annotation (or the older `testMethod` keyword). |
| `static void` with no parameters | Required signature. A test method cannot take arguments or return a value. |
| Name `DiscountCalculatorTest` | A convention: class name plus `Test`. Nothing enforces it, but it makes the class easy to find. |
The older style static testMethod void name() still compiles. Use @isTest in new code, because it works the same way on classes and methods.
What the platform does around each method
Every test method runs in its own isolated context.
- Database changes roll back. Any records your test inserts or updates are discarded when the method ends. They never reach the org's real data.
- Governor limits are per method. Each test method starts with a fresh set of limits, so one heavy test does not use up the budget of the next.
- Order is not guaranteed. Methods in a class may run in any order, and one method must never depend on another having run first.
- Org data is hidden by default. Tests cannot see existing records unless the class uses
@isTest(SeeAllData=true). A few setup objects, such asUserandProfile, are still queryable. You should create the data you need yourself, which a later chapter covers.
The arrange, act, assert pattern
A well-formed test method has three phases, even when they are only one line each.
- Arrange. Build the inputs: variables, records, mocks.
- Act. Call the one piece of code you are testing.
- Assert. Compare the actual outcome with the expected one.
appliesPercentageDiscount is a minimal case. The call to DiscountCalculator.apply(100, 10) is the act step, and Assert.areEqual is the assert step. There is no arrange step because the inputs are literals.
Keep one behavior per method. If appliesPercentageDiscount also checked the error cases, a failure would not tell you which behavior broke. A name that states the behavior, such as rejectsPercentOutOfRange, makes the test report readable on its own.
Testing an exception correctly
Look at the second test again.
try {
DiscountCalculator.apply(100, 150);
Assert.fail('Expected an IllegalArgumentException');
} catch (IllegalArgumentException e) {
Assert.isTrue(e.getMessage().contains('between 0 and 100'), 'Unexpected message: ' + e.getMessage());
}Three details matter here:
- If
applyreturns normally, execution reachesAssert.fail, which fails the test. Without that line, a missing exception would let the test pass silently. Assert.failthrows anAssertException. That is not anIllegalArgumentException, so thecatchblock does not swallow it. If you catch a broadExceptioninstead, your ownAssert.failwould be caught and the test would pass when it should not.- Checking the message separates the two validation branches. Both throw
IllegalArgumentException, so the type alone does not tell you which branch fired.
What these tests cover
Coverage counts executable lines that ran at least once during a test run. The class has five executable lines: the two if statements, the two throw statements and the return.
appliesPercentageDiscountruns bothiflines and thereturn.rejectsPercentOutOfRangeruns bothiflines and the secondthrow.- Together they cover four of five lines. The
throwin the null check never ran.
Coverage tools report lines, not behaviors. To reach the missing line, add a third method for the null case.
@isTest
private class DiscountCalculatorNullTest {
@isTest
static void rejectsNullInput() {
try {
DiscountCalculator.apply(null, 10);
Assert.fail('Expected an IllegalArgumentException');
} catch (IllegalArgumentException e) {
Assert.isTrue(e.getMessage().contains('required'), 'Unexpected message: ' + e.getMessage());
}
}
}In a real project you would put this method in DiscountCalculatorTest alongside the others. It sits in its own class here only so the snippet compiles as shown.
Helper methods and inner classes
A test class may contain code that is not a test. Methods without @isTest are never run as tests by the runner, so you can use them as helpers. A small private helper that builds a valid record keeps the arrange phase short and consistent.
@isTest
private class AccountHelperExampleTest {
private static Account buildAccount(String name, Decimal revenue) {
return new Account(Name = name, AnnualRevenue = revenue);
}
@isTest
static void helperBuildsAccountWithoutSavingIt() {
Account a = buildAccount('Acme', 5000);
Assert.isNull(a.Id, 'An unsaved record has no Id');
Assert.areEqual(5000, a.AnnualRevenue, 'Revenue should be set from the argument');
}
}Inner classes are also allowed. You will use them later for things such as HttpCalloutMock implementations, which live inside the test class so production code never sees them.
Common errors
- Returning a value or taking a parameter. The method then fails to compile as a test, or it is silently ignored by the runner. Keep the signature
static void name(). - Forgetting
@isTeston the method. The class compiles, but the method never runs, and coverage drops without any error message. - Relying on method order. If test B reads a record that test A inserted, B fails on the first run where order changes. The rollback means B would not find the record anyway.
- Assuming org data exists. A query for an existing record returns nothing, because tests do not see it. Create what you need inside the test.
- Calling production code with no assertion. The test passes and raises coverage, but it checks nothing. The next chapters cover why that is a problem.
Putting it together
When you write a new test class, follow this order:
- Create a private class named after the class under test, with
@isTest. - Write one
static voidmethod per behavior, each marked@isTest. - In each method, arrange the inputs, act with one call, and assert on the result.
- Add a test for each failure path, and use
Assert.failto catch a missing exception. - Run the tests and check which lines remain uncovered. Add a test for the behavior behind each uncovered line, not just a call that touches it.
Exercise
A test method calls DiscountCalculator.apply(100, -5) inside a try block. The catch block catches Exception e and asserts that the message contains 'between 0 and 100'. The test has no Assert.fail after the call. Name two ways this test can pass when it should not.
Show answer
First, if apply returned normally, nothing would fail, because without Assert.fail a missing exception goes unnoticed. Second, even with Assert.fail added, catching the broad Exception type would catch the AssertException that Assert.fail throws. The message check would then fail, but only by accident. Catch the specific IllegalArgumentException and put Assert.fail right after the call.
Exercise
A test class has two methods. insertsRecord inserts an Account named 'Acme'. findsRecord queries for Account 'Acme' and asserts it exists, with no insert of its own. Why does findsRecord fail, even if insertsRecord runs first?
Show answer
Each test method's database changes are rolled back when the method ends, and tests also cannot depend on execution order. findsRecord must create its own Account (or get it from shared setup that the platform provides to every method) before querying.