2

I need to test that when I share a record, inactive users are skipped, so I must create a user with IsPortalEnabled = true. I have checked to make sure that I, the logged in user, have a role and am an Admin. I have created a User with the last name of 'NonPortalUser,' System Admin Profile, and a Role. I have used DataLoader to output all of the the users and retrieved the NonPortalUser's OwnerId then hardcoded the assignment of that OwnerId to the Account that is associated with the Community. I have used myself and the NonPortalUser in my System.runAs() calls. I verified that my Guest Users in the Community have a Custom Profile set up.

How can I resolve this error?

Test Class:

@isTest
public class CoopDollarsTriggerHandler_Test2 {
    static List<Id> createAccountsAndContacts(){
        List<Contact> contactsToUse = new List<Contact>();
        List<Account> accountsToUse = new List<Account>();

        PartnerTestDataUtility newPartnerTestData = new PartnerTestDataUtility();
        accountsToUse = newPartnerTestData.createAccounts();
        System.debug('!*!*!*! accountsToUse !*!*!*!' + accountsToUse);

        id distributorId;
        distributorId = accountsToUse[1].Id;
        id distributorId1;
        distributorId1 = accountsToUse[0].Id;
        contactsToUse = newPartnerTestData.createContacts(accountsToUse);
        System.debug('!*!*!*! contactsToUse !*!*!*!' + contactsToUse);

        id contact3Id;
        id contact1Id;
        id contact2Id;
        contact3Id = contactsToUse[2].Id;
        contact1Id = contactsToUse[0].Id;
        contact2Id = contactsToUse[1].Id;
        List<Id> idsToUse = new List<Id>();
        idsToUse.add(distributorId);
        idsToUse.add(contact3Id);
        idsToUse.add(contact1Id);
        idsToUse.add(contact2Id);
        idsToUse.add(distributorId1);
        System.debug('!*!*!*! idsToUse !*!*!*!' + idsToUse);

        return idsToUse;
    }

    static List<Id> createRoleAndUser(List<Id> idsToUse){
        User newPortalUser;
        UserRole role1;
        PartnerTestDataUtility newPartnerTestDataUtility = new PartnerTestDataUtility();
        role1 = newPartnerTestDataUtility.createPartnerUserRole(idsToUse);
        newPortalUser = newPartnerTestDataUtility.createPartnerUser(idsToUse, role1);
        return idsToUse;
    }

    static testMethod void testInsertDollars(){

        User nonPortalUser = [SELECT id, UserRoleId FROM User WHERE LastName = 'NonPortalUser' LIMIT 1];
        System.debug('!*!*!*! nonPortalUser !*!*!*!' + nonPortalUser);
        List<Id> idsToUse = new List<Id>();

        System.runAs(nonPortalUser){
            idsToUse = createAccountsAndContacts();
        }

        System.runAs(nonPortalUser){
            createRoleAndUser(idsToUse);
        }
        test.startTest();
        System.debug('!*!*!*! Starting testInsertDollars !*!*!*!');
        // Code for test here
        test.stopTest();
    }  
}

Utility Class w/Methods for creating Accounts, Contacts, Role, and User:

public without sharing class PartnerTestDataUtility {
    public List<Account> createAccounts(){
        Id accountRecordTypeId;
        List<Account> accountsToReturn = new List<Account>();
        // Get account record type
        List<RecordType> types = [Select Id From RecordType Where SobjectType = 'Account' and Name = 'Distributor'];
        if (types != null && types.size() == 1) {
            accountRecordTypeId = types[0].id;
        }
        // Create Accounts 
        Account dist1 = new Account(
            Name = 'dist1', 
            type = 'Partner',
            RecordTypeId = accountRecordTypeId, 
            BillingStateCode = 'GA', 
            Business_Unit__c = 'South',
        OwnerId = '005e00000047Kxx');            
        insert dist1;
        accountsToReturn.add(dist1);

        Account dist2 = new Account(
            Name = 'dist2', 
            type = 'Partner',
            RecordTypeId = accountRecordTypeId, 
            BillingStateCode = 'GA', 
            Business_Unit__c = 'South',
        OwnerId = '005e00000047Kxx');            
        insert dist2;
    /*            
        User nonPortalUser = [SELECT id FROM User WHERE LastName = 'NonPortalUser' LIMIT 1];
        dist2 = [SELECT Id, Name, IsPartner, OwnerId FROM Account WHERE Id =: dist2.Id];
        System.debug('!*!*!*! dist2 - Before Update !*!*!*!' + dist2);
        dist2.OwnerId = '005e00000047Kxx';
        update dist2;
        System.debug('!*!*!*! dist2 - After Update !*!*!*!' + dist2);
    */            
        dist2 = [SELECT Id, Name, IsPartner, OwnerId FROM Account WHERE Id =: dist2.Id];
        dist2.IsPartner = true;
        update dist2;
        System.debug('!*!*!*! dist2 - After Update !*!*!*!' + dist2);
        accountsToReturn.add(dist2);

    for(Account acts : accountsToReturn){
        if(acts.Owner.UserRoleId == null){
            System.debug('!*!*!*! acts.Owner !*!*!*!' + acts.Owner);
            System.debug('!*!*!*! acts.Owner.UserRoleId !*!*!*!' + acts.Owner.UserRoleId);
            acts.OwnerId = '005e00000047Kxx';
            update accountsToReturn;
        }
    }
    System.debug('!*!*!*! accountsToReturn !*!*!*!' + accountsToReturn);

        return accountsToReturn;
    } 

    public List<Contact> createContacts(List<Account> accountsToUse){
        List<Contact> contactsToUse = new List<Contact>();
        Contact contact1 = new Contact(
            LastName = 'contact1',
            Business_Unit__c = 'South',
            Account = accountsToUse[0],
            email = 'test@hvac.mea.com');
        insert contact1;
        contactsToUse.add(contact1);

         Contact contact2 = new Contact(
            LastName = 'contact2',
            Business_Unit__c = 'South',
            Account = accountsToUse[1],
            email = 'test@hvac.mea.com');
        insert contact2;
        contactsToUse.add(contact2);

        Contact contact3 = new Contact(
            LastName = 'contact3',
            Business_Unit__c = 'South',
            Account = accountsToUse[1],
            email = 'test@hvac.mea.com');
        insert contact3;
        contactsToUse.add(contact3);

        return contactsToUse;
    }

    Public UserRole createPartnerUserRole(List<Id> idsToUse){
        UserRole role2 = new UserRole();
            role2.portalType = 'Partner'; // use 'CustomerPortal' for customer portal roles
            role2.PortalAccountId = idsToUse[0];
            role2.CaseAccessForAccountOwner = 'Read'; //Modify as needed
            role2.OpportunityAccessForAccountOwner = 'Read'; //Modify as needed
        insert role2;
        System.debug('!*!*!*! role2 !*!*!*!' + role2);
        return role2;
    }

    Public User createPartnerUser(List<Id> idsToUse, UserRole role1){
        Profile profileId2 = [SELECT Id FROM Profile WHERE Name = 'Distributor Community User - Commercial' LIMIT 1];
        // Profile profileId2 = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];
        // role1 = [SELECT Id FROM UserRole WHERE PortalType = 'Partner' LIMIT 1];
        Contact contact3 = [SELECT Id, FirstName, LastName FROM Contact WHERE Contact.Id =: idsToUse[1]];
        System.debug('!*!*!*! contact3 !*!*!*!' + contact3);
        User u2 = new User(LastName = 'TestLastName',
                           FirstName='TestFirstName',
                           Alias = 'tln2',
                           Email = 'test@hvac.mea.com',
                           Username = 'testUser2@hvac.mea.com',
                           IsActive = True,
                           ProfileId = profileId2.id,
                           communitynickname = 'newCommunityUser',
                           // UserRoleId = role1.Id,
                           PortalRole = 'Worker',
                           TimeZoneSidKey = 'GMT',
                           LanguageLocaleKey = 'en_US',
                           EmailEncodingKey = 'UTF-8',
                           LocaleSidKey = 'en_US',
                           ContactId = contact3.Id);
        System.debug('!*!*!*! u2 !*!*!*!' + u2);
        insert u2;

        u2 = [SELECT Id, IsPortalEnabled, IsActive FROM User WHERE id =: u2.Id];
        System.debug('!*!*!*! u2 - After Insert !*!*!*!' + u2);
        u2.IsPortalEnabled = true;
        u2.IsActive = false;
        update u2;
        System.debug('!*!*!*! u2 - After Update !*!*!*!' + u2);
        return u2;
    }
}
  • Please try to refrain from using all caps or repeated punctuation (!!!) as some users in this community may perceive such content as rude. I recall this test data being some of the most painful to generate, you may wish to simply test with existing users who fit the criteria. – Adrian Larson Jan 23 '18 at 19:40
  • @AdrianLarson I edited your edit because the last bracket was outside the code block. I had every intention of leaving the rest of your edits, but when I saved it had removed your edits and I didn't realize that would happen. I would have fixed it, but I had to get up and go into a meeting. – AstroLovesCodey Jan 23 '18 at 21:11
  • 1
    Makes sense. Gotcha. Fixing indents can be a bit tricky. Note that once you paste a block in, you can hit the little {} button in the editor and it will auto indent for you. Or you can hit CTRL+K. – Adrian Larson Jan 23 '18 at 21:12
  • Also @AdrianLarson I am trying to avoid hard coding user Ids as I should, but I did break down and create a User and use it's hardcoded OwnerId. That didn't work either. – AstroLovesCodey Jan 23 '18 at 21:18
  • Yeah I noticed that. Try testing using existing User records. You won't need SeeAllData. – Adrian Larson Jan 23 '18 at 21:19
0

I believe that it's not the system.runas() that is the problem here.

It's the Accounts that you created, and the Owner of the Accounts(whoever is running the unit test at the time), and those Owners Roles.

So I'd be debugging something more like: ListOfAccounts[0].Owner.UserRoleId < is this null? (Don't forget to re-soql the accounts after insert, otherwise this will always return null)

To specify the Account Owner, you can do it up creation, or use the system.runas command for the "insert dist1" line. The Owner also needs to be Active.

You can also debug: UserInfo.getUserRoleId() < this should be the Accounts Owners RoleId

Let me know if this points you in the direction you need!

  • I did what you suggested. I assigned the NonPortalUser to OwnerId during the account creation and then check to see if the OwnerId is null and if it is, assign the NonPortalUser as the Owner. When I check my debug logs, I see the following: (See next comment as logs cause this to be longer than available characters) – AstroLovesCodey Jan 23 '18 at 21:46
  • - !*!*!*! nonPortalUser !*!*!*!User:{Id=005e00000047KxxAAE, UserRoleId=00Ei0000000FyajEAC} - !*!*!*! dist2 - After Update !*!*!*!Account:{Id=001e0000016Ld9DAAS, Name=dist2, IsPartner=true, OwnerId=005e00000047KxxAAE} - !*!*!*! acts.Owner !*!*!*!null - !*!*!*! acts.Owner.UserRoleId !*!*!*!null - !*!*!*! accountsToReturn !*!*!*!(Account:{Name=dist1, Type=Partner, RecordTypeId=012i0000000xjAHAAY, BillingStateCode=GA, Business_Unit__c=South, OwnerId=005e00000047KxxAAE, Id=001e0000016Ld9CAAS}, Account:{Id=001e0000016Ld9DAAS, Name=dist2, IsPartner=true, OwnerId=005e00000047KxxAAE}) – AstroLovesCodey Jan 23 '18 at 21:49
  • Code above edited to show my changes. – AstroLovesCodey Jan 23 '18 at 21:55
  • Ok great, 2 things... 1) You should re-soql for accountsToReturn after your DMLs, that's why owner is coming back null; 2) The owner of those accounts should return your "unit test" user(aka the user that is running when you ran your "insert dist1" and "insert dist2" commands). You can also debug: UserInfo.getUserRoleId() < this should be the Accounts Owners RoleId – Mike Katulka Jan 23 '18 at 22:49
0

I have been able to successfully create portal users in my org in the following manner. I don't know if it will work for others, but maybe help!

UserRole role0 = new UserRole();
        role0.CaseAccessForAccountOwner = 'Read'; //Modify as needed
        role0.OpportunityAccessForAccountOwner = 'Read'; //Modify as needed
        role0.Name = 'General Manager';
        insert role0;
        System.debug('!*!*!*! role0 !*!*!*!' + role0);

        Profile profileId0 = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];
        User u0 = new User(LastName = 'TestLastName0',
                           FirstName='TestFirstName',
                           Alias = 'tln0',
                           Email = 'mmueller@exmple.com',
                           Username = 'testUser0@example.com',
                           IsActive = True,
                           ProfileId = profileId0.id,
                           UserRoleId = role0.Id,
                           TimeZoneSidKey = 'GMT',
                           LanguageLocaleKey = 'en_US',
                           EmailEncodingKey = 'UTF-8',
                           LocaleSidKey = 'en_US');
        System.debug('!*!*!*! u0 !*!*!*!' + u0);
        insert u0;

Account dist1 = new Account();
Contact contact3 = new Contact();
Id accountRecordTypeId;
        List<RecordType> accountType = [Select Id From RecordType Where SobjectType = 'Account' and Name = 'Distributor' LIMIT 1];
        if (accountType != null && accountType.size() == 1) {
            accountRecordTypeId = accountType[0].id;
        }
        System.runAs(u0){
            // Create Accounts 
            dist1.Name = 'dist1'; 
            dist1.type = 'Partner';
            dist1.RecordTypeId = accountRecordTypeId;
            dist1.BillingStateCode = 'GA'; 
            dist1.Business_Unit__c = 'South';
            dist1.ownerId = u2.id;
            dist1.pse__ERP_Worker_Correlation_Id__c = 'test';
            dist1.Home_Depot_Vendor__c = 'test';

            insert dist1;
            dist1 = [SELECT Id, Name, IsPartner, OwnerId FROM Account WHERE Id =: dist1.Id];
            dist1.isPartner = true;
            update dist1;
            System.debug('#$#$#$# dist1 #$#$#$#' + dist1);

            contact3.LastName = 'contact3';
            contact3.Business_Unit__c = 'South';
            contact3.Account = dist1;
            contact3.AccountId = dist1.id;
            contact3.email = 'mmueller@example.com';
            insert contact3;
            System.debug('#$#$#$# contact3 #$#$#$#' + contact3);

        User u3 = new User();
        u3.profileId = [select id from profile where name = 'Distributor Warranty User - Partner Logins'].id; 
        u3.LanguageLocaleKey='en_US';
        u3.firstname ='testing user';
        u3.lastname = 'testerson';
        u3.alias = 'ktest1';
        u3.email='nope@example.com';
        u3.communitynickname = 'newCommunityUser';
        u3.TimeZoneSidKey = 'GMT';
        u3.LocaleSidKey = 'en_US';
        u3.EmailEncodingKey = 'UTF-8';
        u3.Username = 'NewPortalUser@example.com';
        u3.IsActive = true;
        // u3.ContactId = c.id;
        u3.ContactId = contact3.id;
        System.debug('#$#$#$# u3 #$#$#$#' + u3);
        insert u3;
        System.debug('#$#$#$# u3 - After Insert #$#$#$#' + u3);

        id coopPermissionSet2 = [SELECT Id FROM PermissionSet WHERE Label = 'Distributor Partner Logins Coop Access'].id;
        System.debug('^&^&^&^&^ coopPermissionSet2 ^&^&^&^&^' + coopPermissionSet2);
        PermissionSetAssignment psa2 = new PermissionSetAssignment(
                    PermissionSetId = coopPermissionSet2,
                    AssigneeId = u3.id);
    }

Apparently, User is a protected object, so Users have to be created within the test class. Thanks to @codefriar for the help guiding me towards a solution on this!

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.