Sub topic 16
Testing Rollback Behavior
This chapter shows how to write Apex tests that prove a rollback happened, and how to avoid tests that pass for the wrong reason. It assumes you can write a basic @IsTest class, you know Database.setSavepoint and Database.rollback, and you have seen the earlier chapters on caught exceptions, addError, and the DML statement limit.
Why rollback tests are easy to get wrong
Every Apex test method already runs inside a transaction that the platform rolls back when the test finishes. Nothing your test inserts is saved. This keeps the org clean, but it has a side effect. If you assert only that "the record is not there", you can't tell whether your code rolled back or whether the test never created the record.
A useful rollback test has three parts:
- Arrange: set up a state you can measure, such as a record count.
- Act: run the code that should roll back.
- Assert: compare the state to what you measured, and check that the failure was the one you intended.
The last two steps matter most. A rollback test that still passes without the rollback proves nothing.
The basic savepoint test
The simplest test counts records before and after a rollback.
@IsTest
private class RollbackTest {
@IsTest
static void rollbackRemovesInsertedRecord() {
Integer before = [SELECT COUNT() FROM Account];
Savepoint sp = Database.setSavepoint();
insert new Account(Name = 'Temp');
Assert.areEqual(before + 1, [SELECT COUNT() FROM Account]);
Database.rollback(sp);
Assert.areEqual(before, [SELECT COUNT() FROM Account]);
}
}The middle assertion confirms the insert worked. Without it, a failed insert would make the final assertion pass trivially.
By default a test cannot see existing org data, so before counts only records the test created. Taking the baseline anyway keeps the test correct if someone adds a test setup method later.
Testing production code that rolls back
Testing the Apex language is less useful than testing your own code. Suppose a service creates an account and a contact together and rolls both back if either fails.
public class AccountContactService {
public static Id 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 acct.Id;
} catch (DmlException e) {
Database.rollback(sp);
throw e;
}
}
}The test passes a null last name, which makes the contact insert fail with a required-field error.
@IsTest
private class AccountContactServiceTest {
@IsTest
static void failedContactRollsBackAccount() {
Integer before = [SELECT COUNT() FROM Account];
Boolean threw = false;
try {
AccountContactService.createWithContact('Acme Test', null);
} catch (DmlException e) {
threw = true;
Assert.areEqual(
StatusCode.REQUIRED_FIELD_MISSING,
e.getDmlType(0)
);
}
Assert.isTrue(threw, 'Expected a DmlException');
Assert.areEqual(before, [SELECT COUNT() FROM Account]);
}
}The test catches the exception. This is why the rollback assertion means something. A caught exception does not undo earlier DML, so if the service forgot Database.rollback, the account would stay and the final assertion would fail. If the test let the exception escape, the platform would roll back the whole test transaction and hide the bug.
Checking getDmlType(0) confirms the test failed for the reason you intended. A different failure, such as a missing account name, would otherwise pass the test for the wrong reason.
Testing that a caught exception keeps earlier work
You can also write a test that documents the surprising behavior from the earlier chapter on handled exceptions.
@IsTest
private class HandledExceptionTest {
@IsTest
static void caughtExceptionKeepsEarlierInsert() {
insert new Account(Name = 'Kept');
try {
insert new Account(); // Name is required
Assert.fail('Expected a DmlException');
} catch (DmlException e) {
Assert.isTrue(e.getMessage().contains('REQUIRED_FIELD_MISSING'));
}
Assert.areEqual(1, [SELECT COUNT() FROM Account WHERE Name = 'Kept']);
}
}Assert.fail sits inside the try block. It throws an AssertException, not a DmlException, so the catch clause does not swallow it.
Testing partial success and triggers
For Database.insert(records, false), assert on the SaveResult list, not on exceptions. Nothing is thrown.
@IsTest
private class PartialSuccessTest {
@IsTest
static void goodRecordSavesBadRecordReported() {
List<Account> accts = new List<Account>{
new Account(Name = 'Good'),
new Account()
};
Database.SaveResult[] results = Database.insert(accts, false);
Assert.isTrue(results[0].isSuccess());
Assert.isFalse(results[1].isSuccess());
Assert.areEqual(
StatusCode.REQUIRED_FIELD_MISSING,
results[1].getErrors()[0].getStatusCode()
);
Assert.areEqual(1, [SELECT COUNT() FROM Account]);
}
}The same approach works for the addError trigger from earlier. With the all-or-none form you can assert that the whole statement fails.
@IsTest
private class ContactTriggerTest {
@IsTest
static void missingEmailBlocksWholeStatement() {
List<Contact> contacts = new List<Contact>{
new Contact(LastName = 'Has Email', Email = '[email protected]'),
new Contact(LastName = 'No Email')
};
try {
insert contacts;
Assert.fail('Expected a DmlException');
} catch (DmlException e) {
Assert.isTrue(e.getMessage().contains('Email is required'));
}
Assert.areEqual(0, [SELECT COUNT() FROM Contact]);
}
}The valid contact is not saved either, because all-or-none DML fails the whole statement when any record fails.
Testing what a rollback does not revert
Rollback gaps are a common source of production bugs, and tests can pin them down. This test checks two of them: a static variable and the Id left on the in-memory record.
@IsTest
private class AfterRollbackStateTest {
private static Integer counter = 0;
@IsTest
static void staticVariableSurvivesRollback() {
Savepoint sp = Database.setSavepoint();
counter++;
insert new Account(Name = 'Temp');
Database.rollback(sp);
Assert.areEqual(1, counter);
}
@IsTest
static void idRemainsOnRolledBackRecord() {
Savepoint sp = Database.setSavepoint();
Account a = new Account(Name = 'Temp');
insert a;
Database.rollback(sp);
Assert.isNotNull(a.Id);
Assert.areEqual(0, [SELECT COUNT() FROM Account WHERE Id = :a.Id]);
a.Id = null;
insert a;
Assert.areEqual(1, [SELECT COUNT() FROM Account WHERE Id = :a.Id]);
}
}If your own code reuses a rolled-back record, add a test like the second one. It fails if the code forgets to clear the Id.
Testing savepoint invalidation and limit cost
Rolling back to an earlier savepoint invalidates later ones. The test below expects a runtime error. It catches the general Exception type, so it does not depend on which exception class the platform raises.
@IsTest
private class SavepointBehaviorTest {
@IsTest
static void laterSavepointIsInvalidAfterEarlierRollback() {
Savepoint sp1 = Database.setSavepoint();
insert new Account(Name = 'A');
Savepoint sp2 = Database.setSavepoint();
insert new Account(Name = 'B');
Database.rollback(sp1);
Boolean failed = false;
try {
Database.rollback(sp2);
} catch (Exception e) {
failed = true;
}
Assert.isTrue(failed, 'Expected the later savepoint to be invalid');
}
@IsTest
static void savepointAndRollbackCountAsDml() {
Integer start = Limits.getDmlStatements();
Savepoint sp = Database.setSavepoint();
insert new Account(Name = 'Temp');
Database.rollback(sp);
Assert.areEqual(3, Limits.getDmlStatements() - start);
}
}The second test records the limit cost: one statement for the savepoint, one for the insert, and one for the rollback. If you set savepoints in a loop, a similar test with many records shows how fast you approach the limit of 150 DML statements.
Asynchronous code and callouts
Code in batch, queueable, and future methods runs in its own transaction. In a test, wrap the call in Test.startTest() and Test.stopTest(). At stopTest the platform runs the queued work synchronously, and you can then assert on its result. Assertions placed before stopTest see the state before the job ran. Test.startTest() also resets governor limits, so take limit measurements inside the block.
Tests cannot make real callouts. Use Test.setMock with an HttpCalloutMock. Because of the uncommitted work pending error, a test that does DML and then a callout in the same transaction fails unless you place the DML before Test.startTest(). Keeping the setup DML before startTest is the usual fix.
What to assert
| Behavior under test | What to assert |
|---|---|
| Savepoint rollback | Count or query result equals the baseline; expected failure was the one that occurred |
| Caught exception | Earlier DML is still present |
| Partial success | `isSuccess()` per record, error `StatusCode`, count of saved records |
| Trigger `addError` | Message text, and zero saved records for all-or-none |
| Static variables, record `Id` | Value unchanged after rollback |
| Savepoint and rollback cost | Difference in `Limits.getDmlStatements()` |
Exercise
A test calls a service method that inserts an Account, then fails on a Contact insert and rolls back to a savepoint. The test does not catch the exception, and a test-level assertion afterward is never reached. Why is this a weak test, and how do you fix it?
Show answer
The unhandled exception ends the test method, and the platform rolls back the whole test transaction anyway, so the test passes or fails regardless of whether the service called Database.rollback. Fix it by catching the DmlException inside the test, recording that it was thrown, and then asserting that the Account count equals the baseline. A caught exception does not undo DML, so the assertion only passes if the service rolled back.
Exercise
Write the assertion that shows a savepoint plus one insert plus one rollback uses three DML statements, and say what you must capture first.
Show answer
Capture Integer start = Limits.getDmlStatements() before calling Database.setSavepoint. After the rollback, run Assert.areEqual(3, Limits.getDmlStatements() - start). The savepoint, the insert, and the rollback each count as one DML statement.