[SalesForce] CreatedById is null after insert – Test Class

My understanding of CreatedById was that it gets populated on insert, and that it is not nillable. However, I am trying to test some functionality that depends on the field being populated and it is still null, even if I insert it, use system.runAs, and set seeAllData=true.

Is this field simply not accessible in a test method? The gist:

@isTest(seeAllData=true)
static void testCreatedBy()
{
    User currentOwner = new User();
    insert currentOwner;

    Case transferRequest = new Case();

    Test.startTest();
        system.runAs(currentOwner)
        {
            insert transferRequest;
        }
    Test.stopTest();

    system.assertNotEquals(null, transferRequest.CreatedById, 'The Created By field should not be null after insert'); // fails
}

Best Answer

Any updates on a record made upon an insert by an Apex trigger, workflow or something like that, will NOT reflect in the object representation you have in memory of that record. So, as CreatedById is filled upon insertion, you have to query the object again.

transferRequest = [select Id, CreatedById /*, ANYOTHERFIELDS*/ from Case where Id =: transferRequest.Id limit 1];

Then CreatedById won't be null;