Friday 21 June 2024

Create a Community User in the Test Class

Create a Community User in the Test Class 


The process for creating portal test users is more complex than creating standard test users. It may involve additional fields, and security settings.


Step 1: Create Portal Owner User


private static User createPortalAccountOwner() {
//Create a Role Role is mandatory to create a portal user
UserRole portalRole = new UserRole(DeveloperName = 'MyCustomRole', Name = 'My Role', PortalType='None' );
insert portalRole;
System.debug('portalRole is ' + portalRole);
Profile sysProfile = [Select Id from Profile where name = 'System Administrator'];
User portalOwnerusr = new User(
Firstname='Demo',
Lastname='PortalOwner',
UserRoleId = portalRole.Id,
Email='demo.portalowner@test.com',
Username = 'demo.portalOwner' + System.currentTimeMillis() + '@test.com',
ProfileId = sysProfile.Id,
Alias = 'demalss',
EmailEncodingKey='UTF-8',
LanguageLocaleKey='en_US',
LocaleSidKey='en_US',
TimeZoneSidKey = 'America/Los_Angeles'
);
Database.insert(portalOwnerusr);
return portalOwnerusr;
}


Step 2: Create a Community User


private static User createCommunityUser(User portalOwner) {
User communityUser ;
System.runAs ( portalOwner ) {
//Create account
Account acc = new Account(
Name = 'acc',
OwnerId = portalOwner.Id
);
Database.insert(acc);
//Create contact
Contact con = new Contact(
FirstName = 'conFirst',
Lastname = 'conLast',
AccountId = acc.Id,
Email = 'con' + System.currentTimeMillis() + '@test.com'
);
Database.insert(con);
communityUser = new User(
FirstName = 'DemoFirst',
LastName = 'DemoLast',
Email = 'Democommunityuser@test.com',
ProfileId = [SELECT Id FROM Profile WHERE Name = 'Community User Plus User'].Id,
Username = 'Democommunity.user.' + System.currentTimeMillis() + '@test.com',
Title = 'Title',
Alias = 'DemoAls',
TimeZoneSidKey = 'America/Los_Angeles',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ContactId = con.id
);
Database.insert(communityUser);
}
re



Step 3: call below code from the test method: 

User portalOwner = createPortalAccountOwner();
User portaluser= createCommunityUser(portalOwner);