2

I have a APEX Test Method that has started to throw exceptions (don't know if this is related to a new release) but I'm not sure what to do to avoid these exceptions

    // Using this 'user' to avoid Mixed DML Errors
    public static User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];

    static testMethod void testInit() {

        Account a = TestUtils.createAccount('Individual Account', 5, false);
        Account s = TestUtils.createAccount('Org Account', 5, false);
        insert new List<Account> { a, s };

        Contact staff1 = TestUtils.createContact('Staff 1', s.Id, false);
        insert(staff1); 

        // Create Portal User for Contact
        User portalUser = TestUtils.createPortalUser(staff1.LastName, staff1.Email + String.valueOf(Math.random()) + String.valueOf(Math.random()), 'alias', staff1.Id, true, false);

        // Getting an error 'User Must have Role', adding a Role here seems to solve this problem
        portalUser.UserRoleId = [select Id from UserRole where PortalType = 'Partner' limit 1].id;

        // Avoid MIXED_DML_EXCEPTION 
        System.runAs(thisUser){
            insert portalUser;
        }       

        System.runAs(portalUser) {
            Test.startTest();
            Test.setCurrentPage(Page.SchoolFeeWaivers);

            System.debug('testInit');

            // Attempting to insert Contact here causes: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY on `insert`          
            Contact parentA = TestUtils.createContact('Parent A', a.Id, true);

        // ...

So why am I getting an INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY? I'm assuming it has to do with the fact that Account a doesn't have the same owner as the Contact?

If I remove the System.runAs(portalUser) call the code runs fine?

1

The answers to this question seem to indicate that I should create the Account with a user who has a role to avoid the "User Must have Role", but in this case I'm specifically not creating the user I'm going to runAs to avoid MIXED_DML_EXCEPTIONS?

Which led me check my user's profile, which didn't have a ROLE! As a result, when I selected a role for my account, (using the current user context to setup the Account), the error is resolved and the test runs as expected.

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.