You need to sign in to do that
Don't have an account?
Bella
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?
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
Anytime you've got a specific ID in your code, you make it harder to move around. Maybe your code looks like:
What if it were more like
This will work in any org that has a User with that Alias. Of course, use whatever criteria you like in the query.
Jeremy
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...
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?
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
Got it working. Thank you!