Hello
I have come across many times this question how to cover record type in test class,This made me to share in
my blog.Here is the code you can refer
for example :
let say we have two Contact Record Types PrimaryContact and BusinessContact.
Now we can create Contact record by using these recordtype such as PrimaryContact or BusinessContact .
There are two different approach.
RecordType rt = [SELECT id,Name
FROM RecordType
WHERE SobjectType='Contact ' AND Name='PrimaryContact '];
And now use this value further while creating the Contact Record.
Contact con = new Contact (Name='TestConatct' , recordTypeId=rt.id);
INSERT con;
Second Approach
We can do this in other way without query.
Schema.DescribeSObjectResult cfrSchema = Schema.SObjectType.Contact;
Map<String,Schema.RecordTypeInfo> ContactRecordTypeInfo
= cfrSchema.getRecordTypeInfosByName();
Now to get the recordTypeId we will have to use a method getRecordTypeId.
Id rtId = ContactRecordTypeInfo.get('PrimaryContact ').getRecordTypeId(),
Now we can insert Contact Record like
Contact con = new Contact (Name='TestConatct',recordtypeid = rtId );
INSERT con;
I have come across many times this question how to cover record type in test class,This made me to share in
my blog.Here is the code you can refer
for example :
let say we have two Contact Record Types PrimaryContact and BusinessContact.
Now we can create Contact record by using these recordtype such as PrimaryContact or BusinessContact .
There are two different approach.
First Approch
We normally query like this . RecordType rt = [SELECT id,Name
FROM RecordType
WHERE SobjectType='Contact ' AND Name='PrimaryContact '];
And now use this value further while creating the Contact Record.
Contact con = new Contact (Name='TestConatct' , recordTypeId=rt.id);
INSERT con;
Second Approach
We can do this in other way without query.
Schema.DescribeSObjectResult cfrSchema = Schema.SObjectType.Contact;
Map<String,Schema.RecordTypeInfo> ContactRecordTypeInfo
= cfrSchema.getRecordTypeInfosByName();
Now to get the recordTypeId we will have to use a method getRecordTypeId.
Id rtId = ContactRecordTypeInfo.get('PrimaryContact ').getRecordTypeId(),
Now we can insert Contact Record like
Contact con = new Contact (Name='TestConatct',recordtypeid = rtId );
INSERT con;
No comments:
Post a Comment