function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
eswarsfeswarsf 

Autonumber field in test class giving null

Hi,

I have a class in which I am updating a field for a custom object.For this class i have written a test class.In this test class i was creating new record for my custom object.

 

The problem is for this custom object,Name field is an Autonumber field.

So in my test class after inserting i was trying to send this Name to my Apex class.But surprisingly it is giving me NULL after insert in Test class.

 

Kindly let me know if this is a Salesforce defect.

 

Thanks,

Eswar.

Best Answer chosen by Admin (Salesforce Developers) 
MattLacey.ax1065MattLacey.ax1065

Hi eswarsf,

 

As far as I'm aware the only field on a sobject to be populated automatically after an insert is the ID, I believe to get the auto-number value for the name field you'll need to query the object:

 

MyObject__c sNew = new MyObject__c();
insert sNew;

sNew = [select Id, Name from MyObject__c where id = : sNew.id];

 

Matt

All Answers

MattLacey.ax1065MattLacey.ax1065

Hi eswarsf,

 

As far as I'm aware the only field on a sobject to be populated automatically after an insert is the ID, I believe to get the auto-number value for the name field you'll need to query the object:

 

MyObject__c sNew = new MyObject__c();
insert sNew;

sNew = [select Id, Name from MyObject__c where id = : sNew.id];

 

Matt

This was selected as the best answer
alok29novalok29nov

Hi,

 

Try something like this..

 

List<CustomObject__c> newBranches = new List<CustomObject__c>{
 new Branch__c(autonumbername='Enterprise',  code__c='ES'),
 new Branch__c(autonumbername='Banking', code__c='BCM') };
   

insert newBranches;

 

Hope this helps!

eswarsfeswarsf

Hi Matt,

Thanks .It works for me.

MattLacey.ax1065MattLacey.ax1065

Good to hear, glad to be of help!

Sushant ChavanSushant Chavan

The marked answer is incorrect. The transaction is not committed. Hence the fetching fails.