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
dmchengdmcheng 

Can't create portal user for unit testing?

Hello.  I need to run unit tests on code that applies to customer portal users.  I tried to create a portal user in code (instantiate User object, assign it to the portal user profile, then insert) but the code fails with an invalid cross-reference ID at the insert.

 

I presume this means I can't create portal users programmatically and instead have to refer to an existing portal user ID instead?

 

Thanks

David

Best Answer chosen by Admin (Salesforce Developers) 

All Answers

hisrinuhisrinu
This was selected as the best answer
Pradeep_NavatarPradeep_Navatar

Try out the sample code given below :

 

Account accInd = new account(name='individual');

insert accInd ;

Contact contact = new Contact(LastName = 'hello',FirstName = 'World',Email = 'a@dolby.com',AccountId =  accInd.Id);

insert contact;

Profile p = [select id from profile where name = 'Volunteer'];

User u = new User(alias = 'standt',

email='a@dolby.com',

emailencodingkey='UTF-8',

FirstName = 'hello',

lastname='Testing',

languagelocalekey='en_US',

localesidkey='en_US',

IsPortalSelfRegistered = true,

profileid = p.Id,

ContactId = contact.id,

timezonesidkey='America/Los_Angeles',

CommunityNickname = 'Tom',

isActive = true,

username='a@dolby.com');

insert u;

system.runAs(u)

{

      system.debug('<!----- UserID ---->'  + u.id);

}

 

Hope this helps.

dmchengdmcheng

Thanks for the link.  I ended up chosing a solution that didn't require Apex code but it's good to have this link available.

ggeorgeggeorge

can you post the code that worked , for creation of portal users