Sub topic 15
Automating post-refresh setup with SandboxPostCopy
This chapter assumes you can read and write basic Apex, you know what a sandbox refresh does, and you have seen the list of things that change afterwards (usernames, email deliverability, integration endpoints). Here you will turn that manual checklist into code that Salesforce runs for you.
Why automate the checklist
A refresh replaces the sandbox with a fresh copy of its source org. Every setting you changed by hand in the old sandbox is gone. Typical repeat work includes:
- Fixing the email address on your own user record, because the copy appends
.invalidto email addresses. - Loading test users or custom settings.
- Pointing integration records at test endpoints.
- Scheduling jobs that the copy does not start.
Done manually, these steps get skipped or done differently each time. SandboxPostCopy is an Apex interface that lets you attach a class to the sandbox creation or refresh. Salesforce runs that class once, after the copy finishes.
How it works
You write a class that implements SandboxPostCopy. The interface has one method, runApexClass(SandboxContext context). When you create or refresh a sandbox, you pick the class in the Apex Class lookup on the creation form. After the copy completes, Salesforce runs the class inside the new sandbox.
Points to remember about this flow:
- The class runs in the sandbox, not in the source org. It must therefore exist in the source org's metadata so that it is copied. For a Developer sandbox, the class must also be deployed to the source org before you start the refresh.
- It runs as the user who started the creation or refresh.
- It is ordinary Apex and is subject to normal governor limits.
- The class needs a public zero-argument constructor. The default constructor satisfies this if you declare no others.
- An exception in your class does not undo the sandbox. You get a working sandbox that is only partly configured, so write the class defensively and check the result.
The SandboxContext
SandboxContext tells your code which sandbox it is preparing. It has three methods:
| Method | Returns |
|---|---|
| `organizationId()` | The ID of the org the sandbox was created from |
| `sandboxId()` | The ID of the sandbox |
| `sandboxName()` | The sandbox name, such as `dev1` |
The minimal class from the plan logs all three:
global class PrepareSandbox implements SandboxPostCopy {
global void runApexClass(SandboxContext context) {
System.debug('Org ID: ' + context.organizationId());
System.debug('Sandbox ID: ' + context.sandboxId());
System.debug('Sandbox name: ' + context.sandboxName());
}
}The name is the most useful value. Many teams keep one post-copy class and branch on sandboxName(), so qa gets test users and uat gets a different set of settings.
Guarding against running in production
Post-copy code often changes data in ways you would never want in production. Salesforce only calls it during sandbox creation, but the class itself can also be run from Anonymous Apex or another class. Add a guard using the IsSandbox field on Organization:
Organization org = [SELECT Id, IsSandbox FROM Organization LIMIT 1];
if (org.IsSandbox) {
System.debug('Running in a sandbox');
} else {
System.debug('Running in production');
}In a real class, exit early when IsSandbox is false. This is cheap and prevents a bad day.
A practical example
The class below does two things. It restores the running user's email address so that notifications reach a real inbox, and it branches on the sandbox name. Salesforce changes email addresses so the sandbox cannot send messages to real customers, so only restore addresses for users you control.
global class PrepareSandbox implements SandboxPostCopy {
global void runApexClass(SandboxContext context) {
Organization org = [SELECT Id, IsSandbox FROM Organization LIMIT 1];
if (!org.IsSandbox) {
return;
}
System.debug('Preparing sandbox ' + context.sandboxName()
+ ' (' + context.sandboxId() + ')');
restoreRunningUserEmail();
if (context.sandboxName() == 'qa') {
System.debug('Applying QA-specific setup');
}
}
private void restoreRunningUserEmail() {
User u = [SELECT Id, Email FROM User WHERE Id = :UserInfo.getUserId()];
if (u.Email != null && u.Email.endsWith('.invalid')) {
u.Email = u.Email.removeEnd('.invalid');
update u;
}
}
}The guard is a plain return, so the sandbox is untouched if the class is ever run elsewhere. The helper method does nothing when the address is already valid, so running the class twice does no harm.
Writing a test
Apex deployed to production needs test coverage. Salesforce provides Test.testSandboxPostCopyScript to run your class inside a test:
@isTest
private class PrepareSandboxTest {
@isTest
static void runsWithoutError() {
Test.startTest();
Test.testSandboxPostCopyScript(
new PrepareSandbox(),
UserInfo.getOrganizationId(),
UserInfo.getOrganizationId(),
'dev1'
);
Test.stopTest();
User u = [SELECT Email FROM User WHERE Id = :UserInfo.getUserId()];
System.assertNotEquals(null, u.Email);
}
}The method takes the class instance, an organization ID, a sandbox ID, and a name. In a test the IDs are just values you supply, so reusing the current org ID for both is fine.
Common errors and limits
- Mixed DML. Salesforce does not let one transaction change setup objects, such as
User, and non-setup objects, such asAccount, together. If your class needs both, do the setup-object work in the main method and the rest in aQueueablejob started withSystem.enqueueJob, or the reverse. - Class not copied. If the class was not deployed to the source org before the refresh, it will not appear in the lookup. Deploy it first.
- Hardcoded IDs. Record IDs differ between orgs. Look records up by name or a stable key instead.
- Silent failure. The sandbox is available even if the class throws. Check debug logs or an email you send yourself, and verify the result after each refresh.
- Heavy work. Large data loads in the post-copy class hit governor limits. Hand large jobs to
Queueableor Batch Apex. - Secrets. Do not put passwords or keys in the class. It is copied into every sandbox. Store secrets outside the code and set them by hand or from a secure source.
Wiring it in
You select the class when creating or refreshing a sandbox in Setup, in the Apex Class field on the form. The same choice is available whether the source is production or another sandbox. Because the class lives in the source org, cloning a sandbox copies it along with the rest of the code.
Exercise
You refresh a Developer sandbox, and the PrepareSandbox class does not appear in the Apex Class lookup. What is the most likely cause, and how do you fix it?
Show answer
The class does not exist in the source org (production, or the source sandbox for a clone), so it is not part of the copied metadata. Deploy the class and its tests to the source org, then start the refresh again.
Exercise
Your post-copy class inserts an Account and then updates a User record in the same method, and the transaction fails with a mixed DML error. How do you fix it?
Show answer
Split the work so setup and non-setup objects are changed in different transactions. For example, keep the User update in runApexClass and move the Account insert into a Queueable class started with System.enqueueJob, or the other way around.