I am writing test class where I need to create test data for standard case object object and parent object for a custom field in case object. When I do the test run it is giving error at the statement where Case object is associated to parent object

Case is linked to BuildingPermit1 with PermitName field. Please help.

private static Contact Contact1;
private static Case Case1;
private static Building_Permit__c  BuildingPermit;

    //create account
    Account1 = new Account();
    Account1.Name = 'Test Company';
    insert Account1;

    //create Contact
   Contact1 = new Contact();
    Contact1.FirstName = 'Testname';
    Contact1.LastName = 'TLname';
    Contact1.Phone = '6667897867';
    Contact1.Email = 'test@gmail.com';

    //create building permit
    Buildingpermit1 = new Building_permit__c();
       Buildingpermit1.permit_name__c = 'testPermit’;
    insert Buildingpermit1;   

   Case1 = new Case();        
   Case1.Origin = 'Phone';
    Case1.Status = 'New';
   Case1.ContactId = mainContact.Id;
   Case1.Subject = 'test subject';
   Case1.Description = 'test desc';
    if (buildingpermit1.Id != null)
  Case1.Buildingpermit1= Buildingpermit1.Id;  //This is the statement where   
                                               //error shows up
    Insert Case1;
  • There's no need to check if the Id is not null; if it were, your test would have crashed with an exception before that point. – sfdcfox Jan 28 '18 at 18:47
  • Yes. I put that when I got dereferencing null object error.I will remove that later. – Uma N Jan 28 '18 at 18:49

You need to use the API name for the field:

Case1.Permit_Name__c = Buildingpermit1.Id;
  • You are awesome. I tried all other options except this one. I thought it will be different data type.Thank you very much. It worked. Today evening I need to move a fix to production. – Uma N Jan 28 '18 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.