Tuesday, March 20, 2012

Record type for creating test class data in Apex Salesforce

Hello guys ,
We have some important consideration while creating test data in our test classes.
So let say if we need to create a record based on the record type id , what we do normally , we query on record type object based on SobjectType and the record type Name.
for example :
let say we have a Account Record Types A & B Not if we need to create a Account Record with record type A or B . We normally query like this .
RecordType rt = [select id,Name from RecordType where SobjectType='Account' and Name='A' Limit 1];
And now use this value further while creating the Account Record.
Account acc = new Account(Name='Test' , recordTypeId=rt.id);

To avoid this query in test class we can the same in some other manner .
Schema.DescribeSObjectResult cfrSchema = Schema.SObjectType.Account; 
Map<String,Schema.RecordTypeInfo> AccountRecordTypeInfo = cfrSchema.getRecordTypeInfosByName();
Now to get the recordTypeId we will have to use a method getRecordTypeId.
Id rtId = AccountRecordTypeInfo .get('A').getRecordTypeId(),
Now Use can insert Account Record like
Account Acc = new Account(Name='test',recordtypeid=AccountRecordTypeInfo .get('A').getRecordTypeId());
insert Acc;



Thanks
    

2 comments:

  1. Thank you for sharing. This is very helpful! The Schema.Describes are a new area for me, I definitely appreciate you sharing!

    ReplyDelete
  2. Excellent Vijay. Thanks for posting.

    ReplyDelete