Sub topic 1
Anatomy of an Apex test class
An Apex test class is a class whose only job is to run your other code and check the results. This chapter covers the parts every test class has, how a test method runs, and the mistakes that most often stop a first test from compiling or passing. Later chapters cover coverage, assertion choice, test data, and bulk, negative, user-context, callout and asynchronous tests in more detail.
Prerequisites
This chapter assumes you already know:
- Basic Apex syntax: classes, static methods, collections, loops and conditionals.
- SOQL queries and the
insertandupdateDML statements. - Standard objects such as Account and User.
- That Apex runs under governor limits, such as a cap on SOQL queries per transaction.
You also need a Salesforce org where you can deploy Apex. A scratch org or Developer Edition org works well. Deploying to production requires tests to pass, so the habit starts here.
What a test class is
A test class is an ordinary Apex class marked with the @IsTest annotation. Inside it, each method marked @IsTest is a test method. The platform finds these methods, runs each one, and reports pass or fail.
Here is a small class to test and its test class:
public class StringUtil {
public static String initials(String fullName) {
if (String.isBlank(fullName)) {
throw new IllegalArgumentException('Name is required');
}
String result = '';
for (String part : fullName.trim().split(' ')) {
if (String.isNotBlank(part)) {
result += part.substring(0, 1).toUpperCase();
}
}
return result;
}
}
@IsTest
private class StringUtilTest {
@IsTest
static void initialsAreUppercased() {
String result = StringUtil.initials('jane doe');
Assert.areEqual('JD', result, 'Initials should be uppercase letters of each word');
}
}The two classes are shown together for readability. In a real project each class lives in its own file, such as StringUtil.cls and StringUtilTest.cls.
The parts of the example
Each piece of StringUtilTest has a rule behind it.
| Piece | What it does | Rule |
|---|---|---|
| `@IsTest` on the class | Marks the class as test-only code | Test classes are excluded from the org's Apex code size limit, and their code cannot run in normal execution |
| `private` | Limits visibility of the class | Test classes can be `private` or `public`. `private` is the usual choice, since the test runner can still see it |
| `@IsTest` on the method | Marks the method as a test | Without it, the method is just a helper and never runs as a test |
| `static void` | Signature of the method | Test methods must be static, return nothing, and take no parameters |
| `Assert.areEqual(...)` | Checks a result | Takes the expected value, the actual value, then a message |
Naming is up to you, but a name that describes the behavior makes failures easy to read. initialsAreUppercased tells you what broke without opening the file. test1 does not.
The shape of a test method: arrange, act, assert
Most good test methods follow three steps.
- Arrange. Build the inputs and any records the code needs.
- Act. Call the code under test.
- Assert. Compare what happened with what you expected.
The initialsAreUppercased method has no arrange step because the input is a literal. Tests that need records put most of their lines into the arrange step. Keeping the three steps visibly separate makes a test easier to read and to debug.
Expected value comes first in Assert.areEqual(expected, actual, message). If you swap them, the test still passes or fails correctly, but the failure message will label the values backwards and mislead whoever reads it.
How a test method runs
When you run a test class, the platform runs each test method as its own transaction. Understanding that model explains most test behavior.
Three consequences follow from this:
- Data is rolled back. Records you insert in a test method never persist after the test finishes, whether it passes or fails. You can insert freely without cleaning up.
- Methods are independent. One test method cannot see records created by another test method in the same class. Shared data comes from
@TestSetup, which a later chapter covers. - Org data is hidden by default. Test methods do not see the records that already exist in the org, with a few exceptions such as setup objects like users and profiles. Your test must create what it needs.
A test fails when an assertion fails or when any exception is thrown and not caught. A test with no failure passes, even if it checked nothing. That last point is why coverage alone is not proof of quality, and the next chapter returns to it.
Calling the code under test
The test class is a separate class, so it can only call what the class under test exposes. Private members are not visible. If you need to test a private method or read a private field, annotate it with @TestVisible:
public class PriceCalculator {
@TestVisible
private static Decimal applyDiscount(Decimal price, Decimal rate) {
return price - (price * rate);
}
}
@IsTest
private class PriceCalculatorTest {
@IsTest
static void discountReducesPrice() {
Decimal result = PriceCalculator.applyDiscount(100, 0.25);
Assert.areEqual(75, result, 'A 25% discount on 100 should give 75');
}
}@TestVisible makes the member accessible from test code only. Normal callers still cannot reach it. Use it sparingly. If you find yourself exposing many private methods, the better question is usually whether the public behavior is tested well enough.
Helper methods inside a test class
A test class can hold ordinary methods that are not tests. For example, a method that builds a record for several tests:
@IsTest
private class AccountHelperTest {
private static Account buildAccount(String name) {
return new Account(Name = name, AnnualRevenue = 1000);
}
@IsTest
static void builtAccountHasName() {
Account a = buildAccount('Acme');
Assert.areEqual('Acme', a.Name, 'Name should match the argument');
}
}buildAccount has no @IsTest annotation, so the platform does not run it as a test. It can take parameters and return values, which test methods cannot. When the same helper is needed in many classes, move it to a shared factory class. A later chapter in this tutorial builds one.
Running your tests
You can run tests in several ways:
- Developer Console: open Test, then New Run, select the class and click Run.
- VS Code with Salesforce Extensions: use the Run Test links above each class or method.
- Salesforce CLI: run one class and wait for the result.
sf apex run test --class-names StringUtilTest --synchronous --result-format humanThe output lists each method with Pass or Fail, and the message for any failure. Running a single method while you work keeps the feedback loop short. Run the whole suite before you deploy.
Common errors
Most first-time failures come from a short list.
| Symptom | Likely cause | Fix |
|---|---|---|
| Compile error on the test method | Method is not `static`, returns a value, or takes parameters | Use `static void name()` with no parameters |
| Test never appears in the run | Method lacks `@IsTest`, or the class lacks it | Annotate both the class and the method |
| Query returns no rows | Test relies on records that exist in the org | Create the records inside the test or in `@TestSetup` |
| Test passes but proves nothing | No assertion, or assertion always true | Add an `Assert` call that compares real results |
| Test passes in one org and fails in another | Test depends on org data, settings or user | Make the test create everything it needs |
| Confusing failure output | Message missing, or expected and actual swapped | Write a message that states the expectation, and put expected first |
Putting it together
A minimal checklist for a new test class:
- Annotate the class with
@IsTestand make itprivate. - Name it after the class under test, with a
Testsuffix. - Write each test as
@IsTest static voidwith a name that describes the behavior. - Follow arrange, act, assert, and finish every test with at least one
Assertcall. - Create all data the test needs. Do not read org data.
- Run the class and read the output for each method.
Exercise
A teammate writes this test method and it does not compile. Name every problem and show the corrected signature. @IsTest public Boolean checksName(String name) { return StringUtil.initials(name) == 'JD'; }
Show answer
There are three problems. The method is not static, it returns Boolean instead of void, and it takes a parameter. Test methods must be static, return nothing and take no parameters. The method also has no assertion, so even a compiling version would never fail. A corrected version is:
@IsTest
static void initialsForJaneDoe() {
String result = StringUtil.initials('jane doe');
Assert.areEqual('JD', result, 'Initials for jane doe should be JD');
}
Exercise
A test method inserts an Account named 'Acme', and a second test method in the same class queries for 'Acme' and finds nothing. Why, and what is the right way to share data between the two methods?
Show answer
Each test method runs in its own transaction, and the data it creates is rolled back when it ends. The second method never sees the first method's records. To share data, create it once in a method annotated @TestSetup, which runs before each test method's transaction and makes its records available to every test method in the class. Alternatively, build the data in a helper method that each test calls.