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
Jason Carrigan 9Jason Carrigan 9 

INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY on Communities Change Username Page Test

Hi All, I created a visualforce page for Communities users to update their username and email. In real life the page works fine, logging in as a Community user I can update my username and email. However, I can't get the test to pass, because it is throwing the following error:

INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []

Here is the test method:
@isTest static void testChangeUserName() {
        User portalUser = getPortalUser();
        
        System.runAs(portalUser) {    
            mportal_PortalAccountController controller = new mportal_PortalAccountController();
            controller.userAccount.Username = 'TEST_NAME1231241@TEST.COM';
            Test.startTest();
            controller.saveEmailUsername();
            Test.stopTest();
        }
        
        portalUser = [SELECT Id, Username FROM User WHERE ID = :portalUser.Id];
        System.assertEquals('TEST_NAME1231241@TEST.COM', portalUser.UserName.toUpperCase()); //username not changed
    }

Test user setup:
    private static User getPortalUser() {
        Contact c = new Contact(LastName = 'Test');
        Insert c;
        
        Profile p           = [SELECT Id FROM Profile  WHERE Name       = 'CRCPortal' LIMIT 1];
        
        User u = new User(Alias             = 'standt', 
                          Email             = 'standardudsfaser@testorg.com', 
                          EmailEncodingKey  = 'UTF-8', 
                          LastName          = 'Testing', 
                          LanguageLocaleKey = 'en_US', 
                          LocaleSidKey      = 'en_US', 
                          ProfileId         =  p.Id, 
                          TimeZoneSidKey    = 'America/Los_Angeles', 
                          UserName          = 'standarduser1234@testorg.com', 
                          ContactId         =  c.id
                          );        
        insert u;
        return u;
    }

Controller save method:
public void saveEmailUserName() {
            try {
                update userAccount;
                showChangeEmail = false;
            } catch (Exception e) {
                ApexPages.addMessages(e);
                System.debug(LoggingLevel.ERROR, e.getMessage());
            }   
    }


Giving the test user a System Administrator profile lets the test pass, but obviously I want to test as a communities user.

Thanks!
ShashankShashank (Salesforce Developers) 
The portal userr does not have access to one of the sObjects used in the code. Please check the user's profile/role access level for the sObjects.