function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ChickenOrBeefChickenOrBeef 

How to set CreatedById and CreatedDate for test class records?

Hey everyone,

I need to write a test class for a trigger that heavily involves the CreatedById and CreatedDate of a task. I can't input values for these fields in a test class, since they're not writeable.

How can I set the CreatedById and CreatedDate for the insertion of a task record in a test class?

Thanks!
-Greg
Best Answer chosen by ChickenOrBeef
Big EarsBig Ears
As Sonam says above, you can set the "CreatedById" using the system.runAs() methods.

Also - As of Spring '16, you can now set the Created date of a record in test context with test.setCreatedDate(recordId, createdDatetime)

http://docs.releasenotes.salesforce.com/en-us/spring16/release-notes/rn_apex_new_classes_methods.htm#rn_apex_new_classes_methods_changed_classes (http://​http://docs.releasenotes.salesforce.com/en-us/spring16/release-notes/rn_apex_new_classes_methods.htm#rn_apex_new_classes_methods_changed_classes)

All Answers

SonamSonam (Salesforce Developers) 
I think you should be using runas() to create the test record with the createdBy Id of the run as user

reference:
https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dml_non_mix_sobjects_test_methods.htm


Big EarsBig Ears
As Sonam says above, you can set the "CreatedById" using the system.runAs() methods.

Also - As of Spring '16, you can now set the Created date of a record in test context with test.setCreatedDate(recordId, createdDatetime)

http://docs.releasenotes.salesforce.com/en-us/spring16/release-notes/rn_apex_new_classes_methods.htm#rn_apex_new_classes_methods_changed_classes (http://​http://docs.releasenotes.salesforce.com/en-us/spring16/release-notes/rn_apex_new_classes_methods.htm#rn_apex_new_classes_methods_changed_classes)
This was selected as the best answer