+ Start a Discussion
Elsa RousselElsa Roussel 

Unit Test : Details: System.DmlException: Insert failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, portal account owner must have a role: []

Hello,
I have this errore while trying to deploy from the sand box to the production (no error in SB).
I'm setting up a new community with simple portal community licence (role are disable in this licence) and i'm fetching a existing user as the account owner :

adminProfile = [SELECT Id FROM Profile WHERE Name IN ('Administrateur système', 'System Administrator')].Id;
roleId = [SELECT Id FROM UserRole WHERE Name ='XXXX' ].Id;
List <User> ownerpossible = [SELECT Id, Name FROM User WHERE IsActive = True AND UserRoleId =:roleId AND ProfileId= :adminProfile LIMIT 1];

Any idea ?
(I've try this method http://blog.jeffdouglas.com/2010/09/02/error-portal-account-owner-must-have-a-role/ but the user doesn't have a role either)
thx
Terence_ChiuTerence_Chiu
The example from the blog requires a contact record to be created and the Id of the contact record needs to be assigned to User.ContactId. Furthermore, the author of the blog post is running his text within the context of System.runas . Have you try that already ?

 
Amit Chaudhary 8Amit Chaudhary 8
Hi,

I hope you are using RunAs to create the portal user ? like below code:-
Account a = new Account(Name='Test Account Name');
  insert a;

  Contact c = new Contact(LastName = 'Contact Last Name', AccountId = a.id);
  insert c;

  User user = new User();
  user.ProfileID = [Select Id From Profile Where Name='Some Profile'].id;
  user.EmailEncodingKey = 'ISO-8859-1';
  user.LanguageLocaleKey = 'en_US';
  user.TimeZoneSidKey = 'America/New_York';
  user.LocaleSidKey = 'en_US';
  user.FirstName = 'first';
  user.LastName = 'last';
  user.Username = 'test@appirio.com';   
  user.CommunityNickname = 'testUser123';
  user.Alias = 't1';
  user.Email = 'no@email.com';
  user.IsActive = true;
  user.ContactId = c.Id;

  insert user;

  System.RunAs(user) {
    // do all of my tests
  }

Option 1:- Try to use above code
Option 2:- Please add role on your user from which you are doing deployment.

Please let us know if that will help u

Thanks
Amit Chaudhary
Jon SnowJon Snow
To fix this kind of error, you can assign a role to the user who runs the unit test, or run as a user who has a UserRole in test code, like the following code : 
 
UserRole userRole_1 = [SELECT Id FROM UserRole WHERE DeveloperName = 'YourUserRole' LIMIT 1];
Profile profile_1 = [SELECT Id FROM Profile WHERE Name = 'Customer Community Login User' LIMIT 1];
User admin = [SELECT Id, Username, UserRoleId FROM User WHERE Profile.Name = 'System Administrator' AND UserRoleId = :userRole_1.Id LIMIT 1];
User user_1;
System.runAs(admin) {
  Account account_1 = new Account( Name = 'Community'  );
  insert account_1;
  
  Contact contact_1 = new Contact(AccountId = account_1.Id, LastName = 'xgeek');
  insert contact_1;
  
  user_1 = new User( 
    Email = 'yourusername@gmail.com',
    ProfileId = profile_1.Id, 
    UserName = 'yourusername@gmail.com', 
    Alias = 'Test',
    TimeZoneSidKey = 'America/New_York',
    EmailEncodingKey = 'ISO-8859-1',
    LocaleSidKey = 'en_US', 
    LanguageLocaleKey = 'en_US',
    ContactId = contact_1.Id,
    PortalRole = 'Manager',
    FirstName = 'Firstname',
    LastName = 'Lastname'
  );
  insert user_1;
}
Test.startTest();
System.runAs(user_1) {
  System.assertEquals(UserInfo.getUserId(), user_1.Id);
  // your test code for Salesforce Community
}
Test.stopTest();

Reference : https://www.xgeek.net/salesforce/to-fix-portal-account-owner-must-have-a-role-error-in-salesforce-community-unit-test/
Justin Shankle 13Justin Shankle 13
I know this is old but, I figured id answer for those still looking for the answer. The best way I found to find the UserLicense type Id is to query via the developer console. "select Id, Name from UserLicense" This will show you the name and Id of the userLicense you are looking for. If you want to use it in a test class to build a user try this.
 
Id userLicenseId = [ select Id from UserLicense where name = 'USE YOUR LICENSE NAME HERE'].id;
		Id communityprofileId = [select Id from Profile where name='USER YOUR PROFILE NAME HERE' and UserLicenseId=:userLicenseId].id;
       
        Account a = new Account(name ='Test Account') ;
        Database.insert(a); 
       
        Contact con = new Contact(LastName ='test Last', FirstName = 'Test First', AccountId = a.Id,  Email = System.now().millisecond() + 'test@test.com');
        Database.insert(con);  
                  
        User portalAccountOwner = new User(alias = 'test123', email='test123@noemail.com',
                emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
                localesidkey='en_US', profileid = communityprofileId, country='United States',IsActive =true,
                ContactId = con.Id,
                timezonesidkey='America/Los_Angeles', username='tester@noemail.com');
       
        Database.insert(portalAccountOwner);

		Test.startTest();
        system.runAs(portalAccountOwner) {
            // statements to be executed by this test user.
        }
		Test.stopTest();



If you get this error "UNKNOWN_EXCEPTION, portal account owner must have a role: []" it is because your admin user you are logged in as when executing the test does not have a role assigned since the admin user is the one inserting the account in your test. Add a role to your admin user before attempting to run the test.