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
Steve LoftusSteve Loftus 

Community user in a unit test

I need to write a trigger which reassigns a lead to a community user and so need to be able to create a community user in a unit test.

Is this possible?

Does anyone have an example of doing this?
Best Answer chosen by Steve Loftus
pbattissonpbattisson
Hi Steve

you can create USer records in a test in just the same way as creating regular object records. For community users you simply need to set them the correct profile and license information as well as ensuring they have an associated contact record. 

There is a develoepr force article on creating a portal user and using the system.runAs() method here (https://developer.salesforce.com/page/Apex_Testing_with_RunAs) which provides sample code that should get you moving.

All Answers

pbattissonpbattisson
Hi Steve

you can create USer records in a test in just the same way as creating regular object records. For community users you simply need to set them the correct profile and license information as well as ensuring they have an associated contact record. 

There is a develoepr force article on creating a portal user and using the system.runAs() method here (https://developer.salesforce.com/page/Apex_Testing_with_RunAs) which provides sample code that should get you moving.
This was selected as the best answer
Steve LoftusSteve Loftus
Hi pbattisson

Thanks for the help.

I had seen that article before but had not recognised the importance of the precondition of:
  • The user that creates the portal user MUST have a Role.
On top of this, the user which creates the portal user MUST be licensed (ie not a guest). The easiest way I found to do this was to set the profileid of the test user creating the portal user to that of the running user; ie UserInfo.GetProfileId().
tggagnetggagne
But is there a way to unit test classes that use Site methods?  Specifically, I want to see if inside a class i can perform Site.Login() to log-in a user if the class knows their username, password.