I am creating a SandboxPostCopy class that generates some mock data in our sandboxes when we do a refresh.

If I run the class via anonymous window, it works fine and builds all the goodies.

If I run the class when refreshing a sandbox, it fails with:

First error: Insert failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, portal account owner must have a role: []

private static void createCustomerCommunityUser(String contactId) {
            User u = [SELECT Id FROM User WHERE LastName = 'Test Customer Community User' AND IsActive = TRUE];
        }catch (QueryException qe){
            Integer randomNumber = Integer.valueOf((Math.random() * 10000));
            Profile profile = [SELECT Id FROM Profile WHERE Name = 'Program Productions Community'];
            User user = new User();
            user.Alias = 'standt';
            user.Email = '[email protected]';
            user.EmailEncodingKey = 'UTF-8';
            user.LastName = 'Test Customer Community User';
            user.LanguageLocaleKey = 'en_US';
            user.LocaleSidKey = 'en_US';
            user.ProfileId = profile.Id;
            user.TimeZoneSidKey = 'America/Los_Angeles';
            user.Username = '[email protected]' + String.valueOf(randomNumber);
            user.ContactId = contactId;
            insert user;

My research shows that SandboxPostCopy is ran by the Automated Process user who does not have a role by default.


  1. Does anyone know how to either give the Automated Process User a role? Along these lines, I've found how to give this user a Permission Set, but I don't know if that'll resolve the problem or not. I can only do a refresh once every 24 hours, so I can only test so often.
  2. Or how to make the SandboxPostCopy class run as a different user?

This is not an @isTest so I cannot use System.runAs() to run it as a different user.

1 Answer 1


Here's an idea:

  • Define a Platform Event: PostSandboxCopy__e
  • Define a trigger for this Platform Event: PostSandboxCopyTrigger
  • Customize the context user for the Platform Event trigger subscriber to a user other than Automated Process
  • Have your SandboxPostCopy implementation do EventBus.publish(new PostSandboxCopy__e(ContactId__c= xxx, ..));
  • Trigger PostSandboxCopyTrigger calls createCustomerCommunityUser

Note you'll need to define the Platform Event and change its context user, then deploy to PROD before you can do an end-end test via a sandbox copy. You will of course, be able to unit test it before deploying to PROD

I have not tested this, YMMV

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .