I'm trying to create a unit test where a I insert a record with a specific record type

    Student_Records__c endterm = new Student_Records__c();
    endterm.School__c = schl.id;
    endterm.Student__c = ct1.id;
    endterm.Position_in_class__c = 1;
    endterm.Type_Bursary__c = 'Full Bursary';
    endterm.Type_of_Exam__c = 'Test';
    endterm.Date__c = date.today();
    endterm.Number_of_students_in_class__c = 10;

The above code works fine when I run the unit test but when I try add:

   endterm.Recordtype.Name = 'Student Exam Records';

I get an error when I run the test. How can I set the record type of a test record being inserted?

1 Answer 1


You need to set the Id not the name. First fetch the Id

Id stExam = Schema.SObjectType.Student_Records__c.getRecordTypeInfosByName().get('Student Exam Records').getRecordTypeId();

and then assign it

endterm.RecordtypeId= stExam;
  • I would recommend to use getRecordTypeInfosByDeveloperName() instead of getRecordTypeInfosByName() as a best practice as the latter will reference the labels instead of the developer name of the record type.
    – Arthlete
    Commented Apr 19, 2023 at 22:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .