Creating unit tests without interacting with the database – creating fake IDs

I was at dreamforce this year and I saw a session on testing and have looked online everywhere to try to find this trick the guy did. He was creating sObjects to complete dependencies of other sObjects but he did not insert these into the database. All of the objects were only in memory and he created fake IDs so that he could still link objects together and run his code that used IDs to operate on.

This would be huge for me to not have to insert into the database and run all my trigger code that has already been tested. Right now I have a test factory implemented that creates my objects and their dependencies and passes them to subsequent test methods but this is a really coupled design. Being able to do this small trick would allow me to create objects that I need completely in memory, increasing run time and making it much easier to test logic that relies on a large number of related objects.

I have tried a couple things like creating a UserRole Id by prefacing the Id with 00E and then 12 more random letters/numbers and also 15 more random letters and numbers. Maybe there is more depth to the Id field that I am missing. Any help with this would be greatly appreciated.


Here’s the fake ID test utility method as used in my DF13 “Tests and Testability” session:

public class TestUtility
   static Integer s_num = 1;

   public static String getFakeId(Schema.SObjectType sot)
      String result = String.valueOf(s_num++);
      return sot.getDescribe().getKeyPrefix() + 
         '0'.repeat(12-result.length()) + result;

Originally posted here:

And here is a use of it:

Account a = new Account(Id=TestUtility.getFakeId(Account.SObjectType));
Opportunity o = new Opportunity(AccountId=a.Id);

Source : Link , Question Author : Chris , Answer Author : Stephen Willcock

Leave a Comment