I am trying to insert a partner community user in my test class. I have created a contact and associated it to the new user but I'm getting the error : "Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Invalid role assignment.: []"

        accList = new list<Account>{
            new Account(Name = 'CourtierPrincipal', Num_ro_ORIAS__c='12345', RecordTypeId = recordTypeMap.get(AP_Constants.rtAccCompte_Tiers_courtier))
        insert accList;

        contactList = new list<Contact>{
            new Contact(LastName = 'CourtierPrincipal', AccountId = accList[0].Id, RecordTypeId = recordTypeMap.get(AP_constants.rtConContact_Business_courtier))
        insert contactList;

        for(UserRole role:[select Id, DeveloperName from UserRole]){
             roleMap.put(role.DeveloperName, role.Id);

        courtierPrincipal = new User(
                                alias = 'testUsr2'
                                ,profileid = profileMap.get('Principal')
                                ,username=getUserNamePrefix() + 'standarduser2@testorg.com'
                                ,ContactId = contactList[0].Id
                                ,UserRoleId = roleMap.get('PartenaireResponsable')  
        insert courtierPrincipal;

1 Answer 1


usually I use the following codes in apex test for portal user. Try to see if it is the same concept :

  Account portalAccount = new Account(name = 'portalAccount');//create a portal account first
  insert portalAccount;
  Contact portalContact = new contact(LastName = 'portalContact', AccountId = portalAccount.Id); //create a portal contact
  insert portalContact;
  User u1 = new User( email='genelia.dsouza@gmail.com',
                profileid = portalProfileId, 
                UserName='genelia.dsouza@gmail.com' + system.label.PortalEmailSuffix, 
                Alias = 'GDS',
                ContactId = portalContact.Id,
                PortalRole = 'Manager',
                FirstName = 'Genelia',
                LastName = 'Dsouza');

Then make sure the specified role is defined on the user running the test class

  • 1
    It works.!! thanks a lot.. the role of the user running the test was not specified. And the PortalRole on the community user must be specified instead of specifying the UserRoleId :)
    – Melisha
    Sep 2, 2015 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.