(Salesforce) Independent Auto-Number Sequence -Test Option

Let say Account has an auto-number field, called Test and there are 47 account records in your organization, the field value of the last created account is Acc-0000047.

After running an Apex test that creates 9 test accounts,

@istest(SeeAllData=false)
private class TestAutoNum {

@testSetup
private static void setup(){
test.startTest();
List accounts = new List();
for(Integer i=0;i<3;i++){
accounts.add(new Account(Name='Test'+i));
}
insert accounts;
test.stopTest();
}

@istest
private static void test1(){
test.startTest();
List accounts = new List();
for(Integer i=0;i<3;i++){
accounts.add(new Account(Name='Test'+i));
}
insert accounts;
print('test1');
test.stopTest();
}

private static void print(String methodName){
System.debug('From : '+methodName);
for(Account acc : [Select Test__c from Account]){
System.debug(acc.Test__c);
}
}

@istest
private static void test2(){
test.startTest();
List accounts = new List();
for(Integer i=0;i<3;i++){
accounts.add(new Account(Name='Test'+i));
}
insert accounts;
print('test2');
test.stopTest();
}
}

this causes the auto-number sequence to be increased by 9 even though these test records aren’t committed to the database and are rolled back.

Next time you create a non-test account record, its auto-number field value will be Acc-0000057 instead of Acc-0000048, hence, it creates a gap in the sequence.

New Independent Auto-Number Sequence Test Option

A new option has been added to ensure that auto-number fields in your organization’s records don’t have gaps due to test records created in Apex tests.

This option isolates the auto-number sequence used in Apex tests from the sequence used in your organization. As a result, the creation of test data in Apex tests doesn’t cause the sequence of auto-number fields to be higher for new non-test records in your organization.

You can enable this option from Setup by clicking Develop | Apex Test Execution | Options…, selecting Independent Auto-Number Sequence, and clicking OK.

Let’s run the test again.

and create a new account. It should be having Acc-0000058.

There are some Glitches.

  1. When you enable Independent Auto-Number Sequence Test Option, the auto number sequence gets reset for every transaction. Since @testSetup runs in a different context, it should be a separate transaction from the unit test. Hence, the unit test itself gets a fresh sequence.
  2. The gap in the auto-number sequence can still occur in other situations, for example, when triggers that attempt to insert new records fail to execute and records are rolled back. In this case, gaps can’t be completely avoided because, in the same transaction, some records can be successfully inserted while others are rolled back.

--

--