Find your content:

Search form

You are here

How do you create an object by a specific user in a unit test?

 
Share

I have a trigger that examines the creator of a Case object and executes code if it matches a user in a specific list. I need to unit test this code, and so I need to create a Case object, but have the CreatedBy field match the user of my choosing.

However, the CreatedById field is set automatically upon creation of the case, and is not editable. How can I unit test this code?


Attribution to: Cory Klein

Possible Suggestion/Solution #1

Use the System.runAs() method to execute test code as another user:

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_testing_tools_runas.htm


Attribution to: Bob Buzzard

Possible Suggestion/Solution #2

Ask Support to enable a feature for you that allows you to set CreatedById on inserts. Then, simply set it to the user's ID in your test method.


Attribution to: JLiljegren__c
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/4416

My Block Status

My Block Content