I ran into this while writing unit tests for my org but I simplified it in a developer account to make sure it would happen there.
I have custom object Thing__c
. The Name
field is autonumber. I wrote the following unit test:
static testMethod void myUnitTest() {
List<Thing__c> things = new List<Thing__c> {
new Thing__c(), new Thing__c(), new Thing__c()
};
insert things;
List<Thing__c> queriedThings = [select name from Thing__c];
for (Thing__c thing : queriedThings) {
system.debug('+++ ' + thing.Name);
}
}
And the relevant log lines are as follows:
+++ C-100000
+++ C-100001
+++ C-100002
So then I add a @testSetup
method, and my test class looks in full like this:
@isTest
private class ThingTest {
@testSetup()
static void setup() {
List<Thing__c> things = new List<Thing__c> {
new Thing__c(), new Thing__c(), new Thing__c()
};
insert things;
}
static testMethod void myUnitTest() {
List<Thing__c> things = new List<Thing__c> {
new Thing__c(), new Thing__c(), new Thing__c()
};
insert things;
List<Thing__c> queriedThings = [select name from Thing__c];
for (Thing__c thing : queriedThings) {
system.debug('+++ ' + thing.Name);
}
}
}
This inserts 6 Things__c
records, so they should be named from C-000000 to C-000005, but they're not. Numbering restarts where it started when creating the first record in the @testSetup
method. Log shows:
"Name":"C-100000","Id":"a0236000002FskaAAC"
"Name":"C-100001","Id":"a0236000002FskbAAC"
"Name":"C-100002","Id":"a0236000002FskcAAC"
"Name":"C-100000","Id":"a0236000002FskdAAC"
"Name":"C-100001","Id":"a0236000002FskeAAC"
"Name":"C-100002","Id":"a0236000002FskfAAC"
If you don't want the repeated numbers then create it all in the test method and use no testSetup annotation. Just call the method manually in each test method. But this, for me, renders @testSetup
not very useful.
Why does this happen? Is this a bug or intended behavior? Is there a way I can use @testSetup
and have autonumbering work as I expect it to?