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
BellaBella 

Testing User Specific Code

I have a piece of code that is only supposed to run if the record was last modified by a user with a specific sf id. It works perfectly in sandbox but the problem is I need to get it into production so I have to have enough test coverage and the test is running as me and I'm not the user. Is there a way I can pretend to have the required Id? To force the test to run as if that user was loged in?

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

You can use System.runAs(user) to masquerade as another user, but this takes a user object as the parameter so you'll need to retrieve the user object that matches the id.

 

Jeremy above makes a good point though - is there a reason why you can't locate the user via a soql query?  Presumably their email address or user id will be unique? 

All Answers

Jeremy.NottinghJeremy.Nottingh

Anytime you've got a specific ID in your code, you make it harder to move around. Maybe your code looks like:

 

ID VIPId = '00x000000342';
if (LastModifiedBy = VIPId) { code }

 

 

What if it were more like

 

ID VIPId = [select id from User where Alias = 'jsmit' ].id;
if (LastModifiedBy == VIPId) { code }

 

This will work in any org that has a User with that Alias. Of course, use whatever criteria you like in the query.

 

Jeremy

 

BellaBella

Mmm I don't think I can really do that. It has to be 1 very specific user. Currently my code looks exactly like your first example with the sf id hard-coded into that varuble...

bob_buzzardbob_buzzard

You can use System.runAs(user) to masquerade as another user, but this takes a user object as the parameter so you'll need to retrieve the user object that matches the id.

 

Jeremy above makes a good point though - is there a reason why you can't locate the user via a soql query?  Presumably their email address or user id will be unique? 

This was selected as the best answer
crop1645crop1645

Try this:

 

Create a Custom Setting of type User Settings. Define a custom field in the Custom Setting that is true only for the user in question.  Then write your test code to fetch the user with this setting = true then do runAs that user.

 

You could also define a custom field on the User object to do this but I like custom settings for their non-counting against SOQL limits

BellaBella

Got it working. Thank you!