Sub topic 2
Why High Coverage Can Still Mean Weak Tests
Assume you know basic Apex syntax, triggers, SOQL, DML, and governor limits. Code coverage tells you which executable lines ran. It does not tell you whether the test checked the result.
Coverage Is Not Test Quality
A test can call a method, execute every branch, and still pass when the method returns the wrong value. This test raises coverage but verifies nothing:
@isTest
private class WeakDiscountCalculatorTest {
@isTest
static void coversLinesButChecksNothing() {
DiscountCalculator.apply(100, 10);
}
}A meaningful test asserts an observable outcome. It also tests important failure paths, such as invalid input. Aim for tests that would fail after a real regression, not tests that only make the coverage percentage higher.
Create Isolated Test Data
Tests should create the records they need instead of depending on records already in an org. By default, Apex tests cannot see ordinary organization data. Avoid SeeAllData=true because it makes tests dependent on configuration and shared records.
A test data factory is a method or class that creates consistent records. Use TestSetup for records shared by several test methods. Salesforce creates this data once for the test class and makes it available to each test in an isolated context.
trigger AccountTrigger on Account (before insert) {
for (Account accountRecord : Trigger.new) {
if (accountRecord.AnnualRevenue != null &&
accountRecord.AnnualRevenue > 1000000) {
accountRecord.Rating = 'Hot';
}
}
}
@isTest
private class AccountTriggerTest {
@TestSetup
static void createSharedData() {
insert new Account(Name = 'Shared test account');
}
private static Account makeAccount(Integer number) {
Decimal revenue = Math.mod(number, 2) == 0 ? 2000000 : 500;
return new Account(Name = 'Bulk account ' + number,
AnnualRevenue = revenue);
}
@isTest
static void marksOnlyHighRevenueAccountsHot() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(makeAccount(i));
}
Test.startTest();
insert accounts;
Test.stopTest();
Integer hotCount = [
SELECT COUNT()
FROM Account
WHERE Id IN :accounts AND Rating = 'Hot'
];
Assert.areEqual(100, hotCount);
}
}Separate the Test Execution
Test.startTest resets governor-limit counters for the operation under test. Test.stopTest ends that scope and runs asynchronous work queued during it. Put the action being measured between these calls. Keep data setup outside the scope when possible.
Prove Bulk Safety
Triggers must handle up to 200 records in one transaction. A single-record test can hide queries or DML statements placed incorrectly inside a loop. The example inserts 200 records and checks that exactly half match the business rule.
Exercise
Why is an assertion necessary when a test already executes every line?
Show answer
Coverage only proves that lines ran. An assertion proves that the resulting behavior is correct.