Sub topic 1
Anatomy of an Apex Test Class
Prerequisites
Assume you know basic Apex classes, methods, collections, SOQL, DML, and Salesforce objects such as Account. You should also understand that governor limits restrict database and computation resources in one transaction.
Test class structure
An Apex test class is marked with @IsTest. Its methods are also marked with @IsTest and are usually static. Salesforce runs these methods separately from normal application code.
Tests should create the records they need. Test data is isolated by default, so tests do not depend on records in the organization.
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 test calls production code, then checks the result. A test that only calls a method without checking its behavior provides weak evidence.
Code coverage
Salesforce generally requires at least 75% Apex code coverage for deployment, and every trigger must have at least one covered line. Coverage measures which lines ran. It does not prove that those lines produced the correct result.
A test can execute every branch and still be useless if it contains no meaningful assertions. Write tests for normal results, boundary values, and expected failures.
Verifying results with the Assert class
The Assert class reports a failure when an expected condition is false. Its message should explain the intended behavior.
Use:
Assert.areEqual(expected, actual, message)for exact values.Assert.areNotEqualwhen two values must differ.Assert.isTrueorAssert.isFalsefor Boolean conditions.Assert.isNullorAssert.isNotNullfor null checks.Assert.isInstanceOfTypefor type checks.Assert.failwhen execution should not reach a statement.
Choosing an assertion
Assert the most specific contract available. Compare a returned status to an expected status with areEqual; use isTrue for a predicate such as startsWith. Avoid asserting implementation details that users cannot observe.
Exercise
What is wrong with a test that calls StringUtil.initials('jane doe') but has no assertion?
Show answer
It may increase code coverage, but it does not prove that the method returned the correct value.