Sub topic 16
Testing Rollback Behavior
This chapter assumes you can write basic Apex test classes, use try/catch with DmlException, and have read the earlier chapters on savepoints and Database.rollback. Rollback logic is easy to get wrong, so it needs tests that prove the data really was undone.
What a rollback test must prove
A useful rollback test checks the database, not only the absence of an exception. The usual shape has three steps:
- Record the state before the work starts, for example a record count.
- Run the code that sets a savepoint, does DML, and rolls back.
- Query again and assert that the state matches the starting point.
Always assert on a fresh query. The in-memory sObject still holds values after a rollback, so checking the variable proves nothing.
A basic rollback test
This test counts accounts before and after a savepoint rollback.
@IsTest
private class RollbackTest {
@IsTest
static void rollbackRemovesInsertedRecord() {
Integer before = [SELECT COUNT() FROM Account];
Savepoint sp = Database.setSavepoint();
insert new Account(Name = 'Temp');
Database.rollback(sp);
System.assertEquals(before, [SELECT COUNT() FROM Account]);
}
}Comparing against before instead of a hard-coded 0 keeps the test valid if the org has data visible to tests.
Testing the code you wrote, not the platform
The test above exercises Database.rollback itself. In practice you test your own method. Put the guarded block in a service method, then call it from the test with input that forces a failure.
public class AccountService {
public static Boolean createWithContact(String acctName, String lastName) {
Savepoint sp = Database.setSavepoint();
try {
Account acct = new Account(Name = acctName);
insert acct;
insert new Contact(LastName = lastName, AccountId = acct.Id);
return true;
} catch (DmlException e) {
Database.rollback(sp);
return false;
}
}
}@IsTest
private class AccountServiceTest {
@IsTest
static void failedContactRollsBackAccount() {
// A null LastName makes the Contact insert fail.
Boolean ok = AccountService.createWithContact('Acme Test', null);
System.assertEquals(false, ok);
System.assertEquals(
0,
[SELECT COUNT() FROM Account WHERE Name = 'Acme Test']
);
}
@IsTest
static void successKeepsBothRecords() {
Boolean ok = AccountService.createWithContact('Acme Test', 'Doe');
System.assertEquals(true, ok);
System.assertEquals(
1,
[SELECT COUNT() FROM Contact WHERE Account.Name = 'Acme Test']
);
}
}The first test covers the failure path. The second covers the success path, so a method that always rolls back would not pass.
Test both sides of the boundary
Cover each behavior covered in earlier chapters:
| Scenario | What to assert |
|---|---|
| Unhandled exception | The test method catches the exception, and earlier DML in the same statement is absent |
| Caught exception without rollback | Earlier DML is still present |
| Rollback to a savepoint | Records inserted after the savepoint are gone, earlier ones remain |
| Partial success with `allOrNone` false | Valid records exist, and failed ones appear in `SaveResult` errors |
Watch the limits inside tests
Tests run under the same governor limits as production code. Each Database.setSavepoint and Database.rollback call counts against the DML statement limit. A test that loops over many records with a savepoint per record can hit the limit, and that is a real signal about your design.
Verify what a rollback does not revert
Rollback leaves the Id on the in-memory record. If your code retries an insert, test that it clears the Id first.
@IsTest
private class StateAfterRollbackTest {
@IsTest
static void idIsStillSetAfterRollback() {
Savepoint sp = Database.setSavepoint();
Account a = new Account(Name = 'Temp');
insert a;
Database.rollback(sp);
System.assertNotEquals(null, a.Id);
System.assertEquals(
0,
[SELECT COUNT() FROM Account WHERE Id = :a.Id]
);
}
}Exercise
A test inserts an Account, sets a savepoint, inserts a second Account, then rolls back to the savepoint. How many of the two Accounts should a fresh query find, and why should you not assert on the second Account's Id being null?
Show answer
A fresh query should find one Account, the first one, because it was inserted before the savepoint. The second Account's Id is not null after the rollback, because a rollback removes the database row but leaves the Id on the in-memory record. Assert with a query instead.