Sub topic 2
Test Data Isolation and `@TestSetup`
Assume basic Apex classes, SOQL, DML, and governor limits. Apex tests normally run with seeAllData=false, so they cannot use existing organization records. Create the records your test needs.
Test data isolation and `@TestSetup`
@TestSetup is a method that creates shared test data once for a test class. Each test method receives an isolated copy of that data. Changes made by one test do not affect another test.
Use setup data for records that many tests need, such as Accounts. Keep data specific to one scenario inside that test.
Building a reusable test data factory
A test data factory is a class with methods that create standard records. It keeps test methods short and makes changes to test data easier to manage.
public class AccountService {
public static void flagLargeAccounts(List<Account> accounts) {
for (Account account : accounts) {
if (account.AnnualRevenue != null &&
account.AnnualRevenue >= 1000000) {
account.Rating = 'Hot';
}
}
update accounts;
}
}
@IsTest
public class AccountTestDataFactory {
public static Account account(String name, Decimal revenue) {
return new Account(Name = name, AnnualRevenue = revenue);
}
}
@IsTest
private class AccountServiceTest {
@TestSetup
static void createData() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
Decimal revenue = Math.mod(i, 2) == 0 ? 2000000 : 500;
accounts.add(
AccountTestDataFactory.account('Test ' + i, revenue)
);
}
insert accounts;
}
@IsTest
static void flagsLargeAccounts() {
List<Account> accounts = [
SELECT Id, AnnualRevenue, Rating FROM Account
];
Test.startTest();
AccountService.flagLargeAccounts(accounts);
Test.stopTest();
Integer hotCount = [
SELECT COUNT() FROM Account WHERE Rating = 'Hot'
];
Assert.areEqual(
100, hotCount, 'Only large accounts should be flagged'
);
}
}Fresh governor limits with `Test.startTest` and `Test.stopTest`
Test.startTest() gives the code under test a fresh set of governor limits. Test.stopTest() ends that measured section and waits for asynchronous work started inside it to finish. Put setup queries and inserts before startTest, then place the service call between both methods.
Testing with 200 records
A bulk test uses many records to expose code that works for one record but fails at scale. Salesforce commonly expects Apex code to handle up to 200 records in one transaction. The example creates 200 Accounts and verifies the result with a new SOQL query.
Exercise
Why should a test query records again after calling the service?
Show answer
The service may update the database. A new query verifies the saved result instead of relying only on in-memory values.