SandboxPostCopy · Salesforce · Salesforcesandboxes · runapex · setup
SandboxPostCopy Apex: Auto-Seeding Sandboxes on Refresh (and Its Limits)
SandboxPostCopy Apex: Auto-Seeding Sandboxes on Refresh (and Its Limits)
Short answer: SandboxPostCopy is a Salesforce Apex interface whose runApexClass(SandboxContext context) method runs automatically once a sandbox is created or refreshed. You name the class when you start the refresh, and Salesforce runs it in the new sandbox. It is ideal for post-refresh clean-up and small amounts of generated data. It cannot pull records from production, so it is not a way to get realistic, related test data.
Every sandbox refresh comes with a checklist: fix integration endpoints, scramble email addresses, reset custom settings, and load some data so the sandbox is usable. Doing it by hand takes hours and gets skipped. SandboxPostCopy lets you write that checklist once in Apex and have Salesforce run it for you.
This guide shows how to set it up, gives a tested seeding example, and explains where it stops being the right tool.
How SandboxPostCopy works
You write a global Apex class that implements the SandboxPostCopy interface and its single method, runApexClass(SandboxContext context). The SandboxContext parameter tells your code where it is running through three methods: organizationId(), sandboxId() and sandboxName(). That lets one class behave differently in, say, a uat sandbox and a dev1 sandbox.
The class must exist in the source org, usually production, because a sandbox is built from that org's metadata. That means it needs the usual test coverage to deploy.
How to set it up
- Write and deploy the class to production, with a test class (below).
- Go to Setup → Sandboxes and click New Sandbox, or Refresh on an existing one.
- Enter the class name in the Apex Class field during the sandbox setup step.
- Create or refresh as usual. When the copy finishes, Salesforce runs your class in the new sandbox.
A working example: seed Accounts and Contacts on refresh
The post-copy class should do as little as possible itself. Here it hands the work to a Queueable job, which runs in its own transaction with its own governor limits.
global class SeedOnRefresh implements SandboxPostCopy {
global void runApexClass(SandboxContext context) {
// Hand off so seeding gets its own transaction and limits
System.enqueueJob(new SeedAccountsJob(context.sandboxName()));
}
}
public class SeedAccountsJob implements Queueable {
private String sandboxName;
public SeedAccountsJob(String sandboxName) {
this.sandboxName = sandboxName;
}
public void execute(QueueableContext qc) {
List<Account> accounts = new List<Account>();
for (Integer i = 1; i <= 50; i++) {
accounts.add(new Account(
Name = 'Seed Account ' + i + ' (' + sandboxName + ')',
Industry = 'Technology'
));
}
insert accounts;
List<Contact> contacts = new List<Contact>();
for (Account a : accounts) {
contacts.add(new Contact(
LastName = 'Contact of ' + a.Name,
AccountId = a.Id
));
}
insert contacts;
}
}Testing it with Test.testSandboxPostCopyScript
Salesforce provides Test.testSandboxPostCopyScript() to run your class in a test as if a sandbox had just been created. Wrapping it in Test.startTest() and Test.stopTest() makes the Queueable run before the assertions.
@isTest
private class SeedOnRefreshTest {
@isTest
static void seedsAccountsAndContacts() {
Test.startTest();
Test.testSandboxPostCopyScript(
new SeedOnRefresh(),
UserInfo.getOrganizationId(),
UserInfo.getOrganizationId(),
'dev1'
);
Test.stopTest();
Assert.areEqual(50, [SELECT COUNT() FROM Account]);
Assert.areEqual(50, [SELECT COUNT() FROM Contact]);
}
}What SandboxPostCopy is good at
The interface shines at environment hygiene: small, predictable changes every sandbox needs after a refresh.
- Pointing integrations at test systems. Update custom settings or custom metadata that hold endpoint URLs, so the new sandbox never calls a production API.
- Scrambling contact emails. Salesforce already appends .invalid to user email addresses in a new sandbox, but not to Contacts and Leads. A post-copy job can do the same for them, so a stray Flow cannot email a real customer.
- Resetting configuration. Turn off features that should not run in test, adjust feature flags, or set sandbox-specific defaults using sandboxName().
- Creating small reference datasets. A handful of Accounts, Products and Price Book Entries so a Developer sandbox is usable on day one.
- Removing what you do not want copied. In Partial Copy and Full sandboxes, delete or anonymise sensitive records that came across from production.
All of these are automatic, consistent and versioned with your code. For hygiene, SandboxPostCopy is the right tool, and every team that refreshes sandboxes regularly should have one.
Here is a hygiene example that scrambles Contact emails in batches, safe on large Partial Copy or Full sandboxes:
public class ScrambleContactEmails implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
'SELECT Id, Email FROM Contact WHERE Email != null'
);
}
public void execute(Database.BatchableContext bc, List<Contact> scope) {
for (Contact c : scope) {
if (!c.Email.endsWith('.invalid')) {
c.Email = c.Email + '.invalid';
}
}
update scope;
}
public void finish(Database.BatchableContext bc) {}
}Start it from your post-copy class with Database.executeBatch(new ScrambleContactEmails());.
The limits of seeding with SandboxPostCopy
Seeding is where the interface runs out of road. Six limits matter.
- It cannot reach production data. The class runs inside the new sandbox. In a Developer sandbox there is nothing to copy from, so any data it creates comes from your code or a static resource. You get invented records, not real ones.
- Relationships are hand-coded. The example above links Contacts to Accounts in a few lines. A realistic Opportunity tree, with Price Books, Products, Quotes, Orders and their line items, means writing and maintaining every link yourself.
- Governor limits still apply. One transaction allows 150 DML statements and 10,000 rows of DML. Anything bigger needs Queueable or Batch Apex, chained jobs and careful error handling.
- It runs only on create and refresh. You can call the class from Anonymous Apex to re-seed, but there is no built-in way to choose records, re-run a seed for one team, or remove what it created.
- No user mapping. Records are owned by whichever user the job runs as. Recreating realistic ownership means matching users in code.
- It is code to maintain. Every new required field or validation rule can break the seed, and a broken seed is easy to miss until someone opens an empty sandbox. Log errors and alert someone when the job fails.
The pattern is clear: SandboxPostCopy is excellent at changing a sandbox and poor at filling one with realistic data.
The better pattern: hygiene in Apex, realistic data from a seeding tool
Split the job in two and use each tool for what it does best.
- Refresh the sandbox with a SandboxPostCopy class that fixes endpoints, scrambles emails, resets configuration and creates a minimal reference dataset.
- Then seed realistic data from production with a seeding tool that runs from the source org. It reads real records, brings their related records along in the right order, maps owners to users in the sandbox, and can remove exactly what it loaded later.
SmartSeed covers the second half: you choose objects and records in production, and it copies them into the sandbox with relationships intact. Save the setup once and re-run it after every refresh. For the full walkthrough, see our complete guide to Salesforce sandbox seeding, and for other options, 5 ways to create test data in Salesforce.
Frequently asked questions
What is SandboxPostCopy in Salesforce? An Apex interface. A class that implements it, with the method runApexClass(SandboxContext context), runs automatically in a sandbox after it is created or refreshed.
Where do I set the SandboxPostCopy class? In Setup → Sandboxes, in the Apex Class field when you create or refresh a sandbox. The class must already exist in the source org.
How do I test a SandboxPostCopy class? Call Test.testSandboxPostCopyScript() with an instance of your class, an org ID, a sandbox ID and a sandbox name. Wrap it in Test.startTest() and Test.stopTest() if the class starts asynchronous jobs.
Can SandboxPostCopy copy data from production? No. It runs inside the new sandbox and only sees that sandbox's data. To bring in specific production records, use a seeding tool or a Partial Copy or Full sandbox.
Can I re-run a SandboxPostCopy class without refreshing? Yes, by calling it from Anonymous Apex, but it is not designed for on-demand reseeding.
Fill your sandboxes with data worth testing
Ready to try it?
The latest SmartSeed release is available to install.
If you're already using SmartSeed, you can upgrade your installation. If you're new, you can explore how SmartSeed helps you prepare realistic Salesforce test data without the repetitive manual work.
Or visit smartseed.app to learn more.
Discover once. Seed multiple environments. Stay in control.