1

I have difficulty to delete Person Account(PA) in Apex test. The reason is that I cannot figure out how to disable the associated user record.

The org has Salesforce SSO and PA feature enabled. Here is my code logic in Apex test:

Test function body:

    Account pa = insertOnePARecord();
    User u = insertOneUserRecord(pa); // relation: user.contactId = pa.PersonContactId

    user.IsPortalEnabled = false; // need to disable the user before deleting PA;
    update user;
    Test.startTest();

    // DML for PA needs to be in a future method
    // Details: https://developer.salesforce.com/forums/?id=906F00000008wAZIAY
    deletePA();
    Test.stopTest();

//

@future
private static void deletePA() {
    system.debug('future--' + user);
    Account pa = [
        SELECT Id, PersonContactId
        FROM Account
        WHERE FirstName = 'John0'
        LIMIT 1
    ];
    delete pa;
}

Error of running the test

Your attempt to delete John0 Doe0 could not be completed because it is associated with the following portal users.: 00d1x0000008ajnuaa20200103162722458811@test00d1x0000008ajnuaa.org

interesting point 1 -- in the dev console of the org, if I set a user.isPortalUserEnabled to false, then delete the corresponding PA record, there is no error.

interesting point 2 -- system.debug() in the future method shows that the user.isPortalUserEnabled value is back to true. How come?

4
  • Maybe because you are referencing the contact in the user record. What happens if you don't do that? Do you need a portal user in your test? Jan 3 '20 at 14:48
  • In the org business logic, all PAs are associated with users. I need to use Apex to delete any given PA record. In addition, it's mysterious why in the future method, the user comes back to live..
    – Xi Xiao
    Jan 3 '20 at 15:01
  • @RenatoOliveira you are right, if I don't link it to a portal user, test goes well. But this doesn't solve my problem as mentioned in the above comment.
    – Xi Xiao
    Jan 3 '20 at 15:07
  • I'm not sure - and won't post this as an answer right now - but I think you should deactivate the user too (set the IsActive field as false). If that doesn't work either, try removing the contact's id from the user record before deleting the contact. Jan 3 '20 at 15:10

Your Answer

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

Browse other questions tagged or ask your own question.