I have a code that is testing a batch, I am creating a contact and an Account , but the contact isn't getting linked to the account (c.AccountId = null). The same code is tested in Async window and it is creating a contact linked to an account.

    Account account = new Account();
    account.RecordType = AccountUtilities.RecordTypes.get('Corporate_Golden_Record');
    account.Name = 'test corp';
    account.phone= '01123123';
    account.billingcountry='United Kingdom';
    account.billingstreet='address 1';
    account.retailer_email__c= '[email protected]';
    insert account;

    //Insert contact for Account
    Contact c = new Contact();
    c.AccountId = account.ID;
    c.FirstName = 'test';
    c.LastName = 'test';
    c.email = '[email protected]';
    c.RecordTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Contact').getRecordTypeId();
    c.Language__c = 'EN';
    c.birthdate = Date.newInstance(1992, 04, 12);
    insert c;

    system.debug('-- Contact : ' + c.Account.Name);
    system.debug('-- Contact : ' + c.ID);


1 Answer 1


The only value that gets updated in the Apex instance for any SObject when you insert is the Id value. Other fields populated as part of the insert by triggers or other logic have to be re-queried to get the values.

The immediate field value will be available just after insert in test class for contact object but in order to access the parent record value you need to re-query the inserted record.

for e.g. If you check account.Name you will get the value but when you will try to get c.Account.Name you need to re query the contact record.

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