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

How to give Record Type in test class

I had to write a record type  in a test class.What i did was I hard coded the record type id.Is is this a proper way or is there any alternate way to do it








Is hard coding a record type a good practice


try this 

Schema.SObjectType.sObjectApiName.getRecordTypeInfosByName().get('Record Type Name').getRecordTypeId();






You need to avoid hardcoding the recordtype ids in your apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail.


Now, to properly handle the dynamic nature of the record type IDs, the following example queries for the record types in the code, stores the dataset in a map collection for easy retrieval, and ultimately avoids any hardcoding.

//Query for the Account record types
     List<RecordType> rtypes = [Select Name, Id From RecordType 
                  where sObjectType='Account' and isActive=true];
     //Create a map between the Record Type Name and Id for easy retrieval
     Map<String,String> accountRecordTypes = new Map<String,String>{};
     for(RecordType rt: rtypes)
      for(Account a:{
     	  //Use the Map collection to dynamically retrieve the Record Type Id
     	  //Avoid hardcoding Ids in the Apex code
     	  	 //do some logic here.....
     	  }else if(a.RecordTypeId==accountRecordTypes.get('High Tech')){
     	  	 //do some logic here for a different record type...

 Please refer for more information.





Hi Kiran,


This is not working.. 

Mohith Kumar ShrivastavaMohith Kumar Shrivastava
Map <String,Schema.RecordTypeInfo> recordTypesadjustment = SampleInventoryTransaction__c.sObjectType.getDescribe().getRecordTypeInfosByName();
    Id RecTypeIdinadj = recordTypesadjustment.get(Label.SFA_InboundRecordType).getRecordTypeId();

 I guess Kiran just missed getDescribe there.No worries Hope this helps.

Hi Steve,
    Please Go through an example in the link (" target="_blank)
Ajay K DubediAjay K Dubedi
Hi steve,
You can't give hardcode id in test class and the following line help to find recordtype Id in test class:
Id RecordTypeIdContact = Schema.SObjectType.Account.getRecordTypeInfosByName().get('RecordTypeContactClientOnly').getRecordTypeId();

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Ajay Dubedi
Varsha Dhage 11Varsha Dhage 11
Thanks Ajay , it helped me. 
pratiksha tamrakarpratiksha tamrakar
Hi kiranmutturu, it helped me.