In this test class: Using System.RunAs user in test class.But It causes below exception

    System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []

 public static string saveCcrRecord(CCR__c record,string ccrtype){
    string result='test';
    User loggedInUser = [Select id,contactId,Contact.AccountId from User where id=:UserInfo.getUserId()];

    string partnerco = loggedInUser.Contact.AccountId;
    record.CCR_Type__c = ccrtype;
    List<AccountTeamMember> accTeamMember = [SELECT AccountId,Id,TeamMemberRole,UserId,User.email,User.Name,User.Phone FROM AccountTeamMember WHERE
                                             AccountId =:partnerco AND TeamMemberRole = 'Sales Engineer' LIMIT 1];
        record.Partner_SE_Name__c = accTeamMember[0].User.name;
            record.Partner_SE_Email__c = accTeamMember[0].User.Email;
            record.Partner_SE_Phone__c = accTeamMember[0].User.Phone;
    } try {  
        //integer dividebyzero=1/0;
        Database.DMLOptions dml = new Database.DMLOptions();
        dml.DuplicateRuleHeader.allowSave = true;
        dml.DuplicateRuleHeader.runAsCurrentUser = true; 
        Database.SaveResult sr = Database.insert(record, dml);
        result = record.Id;

    } catch (Exception e) { 
        result = e.getMessage();
        throw new AuraHandledException(result);
        //system.debug('-----------error message------->'+ result);            

    return result;

Test class:

  Id accountRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Partner/Distributor').getRecordTypeId();
    Account ac=new Account();
    ac.Name='Test Account';
    insert ac;

    contact ct=new contact();
    insert ct;

    Id ccRecordTypeId = Schema.SObjectType.CCR__c.getRecordTypeInfosByName().get('Partner Claim Form').getRecordTypeId();
    CCR__c Cr=new CCR__c();
    Incentives__c incent=new Incentives__c();
    insert incent;
    string Id=incent.id;

    Id p = [select id from profile where name='Partner Community User'].id;

    User user = new User(alias = 'user123', email='user123@noemail.com',
                         emailencodingkey='UTF-8', lastname='users', languagelocalekey='en_US',
                         localesidkey='en_US', profileid = p, country='United States',IsActive =true,
                         ContactId = ct.Id,
                         timezonesidkey='America/Los_Angeles', username='tester@noemail.com');

    insert user;
     // this line causes this issue
        system.debug('user id--->'+user.Id);
        system.debug('account id -->'+ac.id);
       accountteammember atm= new accountteammember();
        atm.teammemberrole='Sales Engineer';
        insert atm;
     PC_IncentiveController.saveCcrRecord(Cr,'Marketing SPIFF');   

I just removed System.runAs(user) in test class.Error is ressoved but itsnot covering below line

List<AccountTeamMember> accTeamMember = [SELECT AccountId,Id,TeamMemberRole,UserId,User.email,User.Name,User.Phone FROM AccountTeamMember WHERE
                                             AccountId =:partnerco AND TeamMemberRole = 'Sales Engineer' LIMIT 1];

accTeamMember value is showing null.


In my case Account Owner was being changed, so there is a custom code written on After Update event of Account. This would take new Account Owner and add Account Share record (Read access) for Account's Parent Account record. In some cases, this new Owner being set on child account would already be there as a Owner on Parent account, and it would cause error INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY.


It appears that your Salesforce org has the Org-Wide Default for Account set to Private. Your test Account is owned by the running user for your test class (whomever actually executes the test).

As a consequence, your test user user cannot see or add Account Team Members to this record - they don't own it, they don't have View All permission on Account, they aren't above the owner in the role hierarchy, etc. There are many routes to obtaining this access, but the user has none of them. This is the source of the error.

What you seem to need to do is two things:

  1. You need to add the AccountTeamMember record in the context of the original running user, rather than the created user, to avoid this permissions issue.
  2. You need to run the code under test (PC_IncentiveController.saveCcrRecord(Cr,'Marketing SPIFF');) as the created test user.

I'm not suggesting that you change your runAs block to the current test user here; I'm suggesting you need to break it up into separate runAs blocks for elements (1) and (2), which need to be run as different users.

  • If you do so we can avoid error..but query in on currently logged in user...that time account team member list size becomes null(accTeamMember). – Annappa Nov 24 '18 at 19:44
  • @AnnappaPH Could you edit your question to show the changes you made? – David Reed Nov 24 '18 at 20:20
  • Updated the question – Annappa Nov 25 '18 at 6:39

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.