Check partial DML results
Prove it with tests · Intermediate · 15 min · Runs in your Salesforce Developer org · Apex Path
Scenario. A bulk service uses partial DML. Its test must tell saved rows from failed rows and check why a row failed.
Insert a good and a bad Account with partial DML, and write a verifier that fails on wrong SaveResults.
What you will learn
Database.insert(rows, false) returns one SaveResult per row. Check isSuccess() first. On success, getId() is the saved Id. On failure, getErrors()[0].getStatusCode() is a StatusCode enum.
Assert.isTrue(results[0].isSuccess());
Assert.isNotNull(results[0].getId());
Assert.areEqual(StatusCode.REQUIRED_FIELD_MISSING,
results[1].getErrors()[0].getStatusCode());
Gotcha. The checks hand yours fake results via JSON.deserialize, so your verifier runs on invented data.
The task
Finish the insert helper and a verifier that fails unless row 1 saved and row 2 failed because Name is missing.
Examples:
- a real insert of a named and a nameless Account → the verifier passes and returns
true - fake results where both rows saved → the test fails with an assert
- fake results where row 2 failed with
DUPLICATE_VALUE→ the test fails with an assert
Requirements:
insertMixedinserts both Accounts withDatabase.insert(records, false)and returns the results.verifyMixedasserts there are 2 results and that row 1 saved with an Id.- It asserts row 2 failed before reading
getErrors(), then asserts the first error's status code isREQUIRED_FIELD_MISSING. - Keep both methods public static. The checks call them directly.
Starter code
@IsTest
public class AS_A3060F564EF1_SaveResultTests {
public static List<Database.SaveResult> insertMixed(String token) {
List<Account> records = new List<Account>{
new Account(Name = 'AS Valid ' + token),
new Account()
};
return new List<Database.SaveResult>();
}
public static Boolean verifyMixed(List<Database.SaveResult> results) {
return false;
}
@IsTest
static void mixedInsert() {
Assert.isTrue(verifyMixed(insertMixed('visible')));
}
}
When it passes
insertMixed returns one success and one REQUIRED_FIELD_MISSING failure. verifyMixed passes on that real outcome and fails with an assert on fake results that are wrong.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.
‹ Test success and exceptions · Reset limits around the act ›