How to generate Database.SaveResult mocks in Salesforce

How to generate Database.SaveResult mocks in Salesforce
Reading Time: < 1 minute

In Salesforce, Database.SaveResult is a class that represents the result of a database operation, such as inserting, updating, deleting, or upserting records. It provides information about the success or failure of the operation, along with any error messages or error codes associated with it.

When performing DML (Data Manipulation Language) operations, such as inserting or updating records, the Database.SaveResult class can be used to retrieve detailed information about each record’s status. It contains properties such as isSuccess to indicate if the operation was successful, getErrors to retrieve any error messages associated with the operation, and getStatusCode to fetch the error code, among others.

By analyzing the Database.SaveResult objects, developers can handle errors, perform custom logic, and provide appropriate feedback to users. This allows for better error handling and ensures data integrity in Salesforce applications.

Let’s say you have a method that processes database errors and you want to add some coverage

public static void processDatabaseSaveResults(Database.SaveResult sr){
   // do something
}

Now you need to cover that method but you realized that Database.SaveResult cannot be instantiated due to the error Type cannot be constructed: Database.SaveResult. One way to generate instances of that class can be:

Database.SaveResult sr = (Database.SaveResult) JSON.deserialize('{"success":false,"errors":[{"message":"test error message","statusCode":"DUPLICATES_DETECTED"}]}', Database.SaveResult.class);

And then you can test it as:

@isTest 
static void shouldTestSomething() {
        // given
        Database.SaveResult sr = (Database.SaveResult) JSON.deserialize('{"success":false,"errors":[{"message":"test error message","statusCode":"DUPLICATES_DETECTED"}]}', Database.SaveResult.class);
        
        // when
        processDatabaseSaveResults(sr);
        
        // then 
        System.assert(...);
        
    }

,

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Join 22 other subscribers

Leave a Reply