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:

static void testCreatedBy()
    User currentOwner = new User();
    insert currentOwner;

    Case transferRequest = new Case();

            insert transferRequest;

    system.assertNotEquals(null, transferRequest.CreatedById, 'The Created By field should not be null after insert'); // fails
  • Can you post your test code?
    – Mike Chale
    Jul 29, 2013 at 16:56
  • Are you running system.runas before you insert the record? Jul 29, 2013 at 16:57
  • Who is currentOwner??? I always try to stay away from using (seeAllData=true). I try to always create my own test data. So i would create a user, insert them. Then create the case, run as that newly created user, and insert. I personally try to always create my own test data Jul 29, 2013 at 17:16
  • It is a user I created in the test. The only reason seeAllData is on is to try to gain visibility to CreatedBy.
    – Adrian Larson
    Jul 29, 2013 at 17:16

1 Answer 1


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;

  • Duh. Ah that's so obvious too.
    – Adrian Larson
    Jul 29, 2013 at 17:24

You must log in to answer this question.

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