Sunday, July 13, 2014

How to Read/Create record types in Apex test class?

How to Read/Create record types in Apex test class?

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;







1 comments:

peter said...

Thank you! Just helped me out.

Post a Comment

 
| ,