There are some scenarios where we need to do unit testing as a Partner Portal/Partner Community user. Below code can be used to create partner portal user and run the logic as that user.
Syntax:
@isTest
private class testClass{
public static testMethod void testFunction(){
//Create account
Account portalAccount1 = new Account(
Name = 'TestAccount'
);
Database.insert(portalAccount1);
//Create contact for the account, which will enable partner portal for account
Contact contact1 = new Contact(
FirstName = 'Test',
Lastname = 'Amit',
AccountId = portalAccount1.Id,
Email = 'test@test.com'
);
Database.insert(contact1);
//Create user for the contact
Profile portalProfile = [SELECT Id FROM Profile WHERE Name = 'Gold Partner User' Limit 1];
User user1 = new User(
Username = 'test12345test@test.com',
ContactId = contact1.Id,
ProfileId = portalProfile.Id,
Alias = 'test123',
Email = 'test12345@test.com',
EmailEncodingKey = 'UTF-8',
LastName = 'Kumar',
CommunityNickname = 'test12345',
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
LanguageLocaleKey = 'en_US'
);
Database.insert(user1);
system.runAs(user1){
Account a = new Account(name='test');
insert(a);
}
}
}
Note:
Syntax:
@isTest
private class testClass{
public static testMethod void testFunction(){
//Create account
Account portalAccount1 = new Account(
Name = 'TestAccount'
);
Database.insert(portalAccount1);
//Create contact for the account, which will enable partner portal for account
Contact contact1 = new Contact(
FirstName = 'Test',
Lastname = 'Amit',
AccountId = portalAccount1.Id,
Email = 'test@test.com'
);
Database.insert(contact1);
//Create user for the contact
Profile portalProfile = [SELECT Id FROM Profile WHERE Name = 'Gold Partner User' Limit 1];
User user1 = new User(
Username = 'test12345test@test.com',
ContactId = contact1.Id,
ProfileId = portalProfile.Id,
Alias = 'test123',
Email = 'test12345@test.com',
EmailEncodingKey = 'UTF-8',
LastName = 'Kumar',
CommunityNickname = 'test12345',
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
LanguageLocaleKey = 'en_US'
);
Database.insert(user1);
system.runAs(user1){
Account a = new Account(name='test');
insert(a);
}
}
}
Note:
- Owner of the user should have a role. so make sure your admin user has a role or you can create one admin user in the test class with appropriate role.
- Make sure partner portal / partner community is enable for your org and respective profile has the access of it.
No comments:
Post a Comment