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

Users to use for unit tests

What's the best way to use users in unit tests?  You can't create temporary users in apex code for unit tests because they are a 'setup entity'.  Should you hardcode some users that are in the system and hope they don't change in the future and break your unit tests?  Should you select the top N users from the user list and just use whoever is returned everytime?
For me, so far I just use the default user with:

but that's mainly because in the test cases I have so far, it doesn't really matter which profile/role I'm getting.  Otherwise I would do a query to get a user of the correct kind.

But this seems way better than hard-coding.  Even between sandbox and production instance, if you hard code you make deployment a real pain.


You have to write tests assuming a base set of users (with correct profiles) already exist.  You can't make them in code.  You have to assume that you have user a with profile x and user b with profile y - and search for them.  You can also use the current logged-in user.

It is interesting to see how this will be handled in the Apex Code packaging through AppExchange.  Presumably all tests scripts will have to run when deploying.   Which will install first?  The profile or the apex code?  And how then will the test users be given the right profiles half-way-through the install?

The easiest answer would seem to be to permit test scripts to create users.  Would be handly in other code too.