How to mock a Database.saveresult?

We need to use database.insertImmediate(). It returns List<Database.SaveResult>.

Now, we want to mock the database.insertImmediate() and not do the dml call and need to be able mock the Database.saveResult as well. Is there any native way to mock it, or should I define an Interface or class that can work with Database.SaveResult?


You can create “fake” system objects, but, of course, be wary of doing so in a way that will break their internal implementation.

Here’s an example of a successful save:

Database.SaveResult sr = (Database.SaveResult)
    JSON.deserialize('{"success":true,"id":"0013000000abcde"}', Database.SaveResult.class);

And a failed save:

Database.SaveResult sr = (Database.SaveResult)
    JSON.deserialize('{"success":false,"errors":[{"message":"You cannot do this...","statusCode":"FIELD_CUSTOM_VALIDATION_EXCEPTION"}]}', Database.SaveResult.class);

You’ll need to figure out a way to inject the values into whatever you’re testing, but without seeing your code, it’s hard to tell exactly how you might do that in your specific case.

Source : Link , Question Author : Jorjani , Answer Author : sfdcfox

Leave a Comment