Sub topic 10
Test Data and Protecting Sensitive Data
This chapter assumes you can create sandboxes and scratch orgs, you know what a definition file is, and you have used the Salesforce CLI. It covers what data each org type holds, how to seed test data, and how to keep production data from leaking into places it should not be.
Why data deserves its own decision
Choosing an org type is also choosing a data policy. A Full sandbox copies production records, so it can hold customer names, emails, phone numbers, and financial details. A scratch org starts with no business data at all. Developers, contractors, and test tools often have wider access to non-production orgs than to production. Sensitive data in those orgs is therefore a real exposure, not a theoretical one.
Two questions guide every decision in this chapter:
- What data does the work need in order to be meaningful?
- Who can see that data once it lands in the org?
What each org type starts with
| Org type | Starting data | Typical risk |
|---|---|---|
| Developer sandbox | Metadata only, no production records | Low. Data is whatever you load. |
| Developer Pro sandbox | Metadata only, more storage | Low. Data is whatever you load. |
| Partial Copy sandbox | Metadata plus a sample of records, selected by a sandbox template | Medium. Real records are present. |
| Full sandbox | Metadata plus all production data, optionally with field history | High. A complete copy of production. |
| Scratch org | Nothing, or sample data if requested in the definition file | Low. Data is whatever you load. |
Check the current storage limits and sampling rules in Salesforce documentation before you plan around them. They change between releases and differ by edition.
Seeding data in a scratch org
A scratch org has no records unless you add them. The definition file has a hasSampleData property. When it is true, the org includes the sample records that Salesforce ships with a new Developer Edition org. When it is false, the org is empty.
{
"orgName": "Acme Development",
"edition": "Developer",
"hasSampleData": false,
"settings": {
"lightningExperienceSettings": {
"enableS1DesktopEnabled": true
}
}
}Sample data is generic and unrelated to your business. For realistic tests, load your own data after the org is created. Keep that data in version control so every developer and every CI run gets the same starting point.
Loading data with the CLI
The Salesforce CLI can import a data plan, which is a set of JSON files that describe records and a plan file that orders them. The sf data import tree command reads those files and creates the records.
sf data import tree --plan data/sample-plan.json --target-org my-scratchA plan file lists the data files and whether references between them should be resolved:
[
{
"sobject": "Account",
"saveRefs": true,
"resolveRefs": false,
"files": ["Account.json"]
},
{
"sobject": "Contact",
"saveRefs": false,
"resolveRefs": true,
"files": ["Contact.json"]
}
]Accounts are listed first with saveRefs set to true. Contacts are listed second with resolveRefs set to true, so a contact can point at an account by reference ID rather than by a real record ID.
{
"records": [
{
"attributes": { "type": "Account", "referenceId": "AccountRef1" },
"Name": "Example Manufacturing"
}
]
}Save that as data/Account.json. A matching data/Contact.json can then use "AccountId": "@AccountRef1" on each contact.
{
"records": [
{
"attributes": { "type": "Contact", "referenceId": "ContactRef1" },
"FirstName": "Pat",
"LastName": "Example",
"AccountId": "@AccountRef1"
}
]
}Every value here is invented. That is the point: seed data that you write yourself carries no privacy risk.
Seeding with Apex
For data that needs logic, such as related records with computed values, you can run anonymous Apex or a script. Keep the script in the repository and run it with the CLI.
sf apex run --file scripts/apex/seed-data.apex --target-org my-scratchList<Account> accounts = new List<Account>();
for (Integer i = 1; i <= 5; i++) {
accounts.add(new Account(Name = 'Test Account ' + i));
}
insert accounts;Anonymous Apex runs within normal governor limits. Large volumes are better loaded with the Bulk API or a data tool.
Controlling what a Partial Copy sandbox contains
A Partial Copy sandbox uses a sandbox template to decide which objects are copied. A template lists objects, and Salesforce copies a sample of records for each. Related objects that the template does not include are not copied.
Use templates to reduce exposure as well as storage. If a task does not need Case or Opportunity records, leave them out of the template. Data that is never copied cannot leak.
You can reference a template in the sandbox definition file with the templateId property when you create a Partial Copy sandbox from the CLI.
{
"sandboxName": "qa1",
"licenseType": "Partial",
"templateId": "0EM000000000000"
}The templateId value above is a placeholder. Use the ID of a template that exists in your production org.
Protecting data in sandboxes
When a sandbox contains real records, assume they need protection. Several controls apply together.
Sandbox Data Mask
Salesforce offers a data masking product, Data Mask, that replaces sensitive field values in a sandbox after a copy. It can scramble, replace, or delete values in fields you choose. It is licensed separately and has its own setup, so confirm availability for your contract. Masking runs on the sandbox, not in production, so the unmasked data exists briefly after the copy completes. Restrict access until masking finishes.
Limit who can log in
A new sandbox copies users from production, and each user's email address is changed so that the sandbox does not send messages to real people. Salesforce appends .invalid to the email address. Do not undo this casually.
Beyond that, review who needs access. Many teams keep the copied users but deactivate or reassign profiles for anyone who has no reason to be in the sandbox. A SandboxPostCopy class can do this automatically.
Outbound messages and integrations
Real data in a sandbox often comes with real integration endpoints. A workflow outbound message, a named credential, or a scheduled job can send sandbox activity to a live production system or an external service. Common examples are billing platforms and marketing email tools.
Review these after each refresh:
- Named credentials and external credentials that point at production endpoints.
- Scheduled Apex jobs that call external services.
- Email deliverability, which a sandbox sets to system email only by default. Leave it that way unless you have a reason.
Using SandboxPostCopy for repeatable protection
A class that implements SandboxPostCopy runs automatically after a sandbox is created or refreshed. It is the right place to put protection steps, so that they happen every time and do not depend on someone remembering.
global class PrepareSandbox implements SandboxPostCopy {
global void runApexClass(SandboxContext context) {
System.debug('Sandbox ' + context.sandboxName() + ' (' + context.sandboxId() + ') copied from org ' + context.organizationId());
// Add post-refresh setup here, such as adjusting settings or seeding test records.
}
}You select the class when you create or refresh the sandbox. It runs once per copy, as an automated process, and a failure does not undo the copy. Write it so that it is safe to run again, and log failures where an administrator will see them.
Typical contents:
- Deactivate or freeze users who do not need access.
- Replace endpoint URLs in custom settings or custom metadata with test endpoints.
- Delete or anonymize specific fields that Data Mask does not cover.
- Insert a known set of test records.
Keep the class small and test it. A post-copy class that throws an unhandled exception may leave the sandbox half configured, and the failure is easy to miss.
Data across the pipeline
Data protection is easier when each stage of your pipeline has a clear data rule.
Early stages hold the least sensitive data and change most often. Later stages hold more realistic data and change less often. Data only flows backward, from production into sandboxes, and always through the refresh and masking steps. It never flows forward from a lower environment into production by hand.
Choosing a data strategy by task
| Task | Suggested data | Reason |
|---|---|---|
| Building a new feature | Synthetic data in a scratch org or Developer sandbox | Fast, repeatable, and no privacy risk |
| Automated unit tests | Records created inside the tests | Apex tests do not see org data by default |
| User acceptance testing | Partial Copy with a template, masked | Realistic shapes without full exposure |
| Performance or load testing | Full sandbox, masked | Volume and data skew match production |
| Training | Developer or Partial Copy with curated data | Predictable examples for learners |
Apex tests deserve a note. Test methods run with data isolation: they do not see existing org records unless the test uses @SeeAllData=true, which you should avoid. Create the records a test needs inside the test, using a test data factory class. This keeps tests independent of whatever data an org happens to hold.
@IsTest
public class TestDataFactory {
public static List<Account> createAccounts(Integer count) {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < count; i++) {
accounts.add(new Account(Name = 'Factory Account ' + i));
}
insert accounts;
return accounts;
}
}Common mistakes
- Treating a sandbox as safe because it is not production. A Full sandbox is a copy of production data. Apply production-level care until masking is done.
- Skipping masking after a refresh. Each refresh recopies unmasked data. Masking must run every time, ideally automatically.
- Leaving integrations pointed at production. Check named credentials and scheduled jobs after every copy.
- Committing real data to version control. Data plans in the repository must contain invented values only.
- Relying on
@SeeAllData=true. Tests then depend on org contents and fail when data changes. - Using
hasSampleDataas a test strategy. Sample data is generic. Use it for exploring, not for verifying your business logic.
Exercises
Exercise
A team needs a sandbox to test a data migration against production-like volumes. They also have a policy that developers must not see real customer emails. Which sandbox type fits, and what must they do after each refresh?
Show answer
A Full sandbox fits, because it copies all production data and so matches production volume and data skew. After each refresh they must mask sensitive fields, for example with Data Mask run from a SandboxPostCopy process or an immediate follow-up step, restrict access until masking finishes, and review integrations and scheduled jobs that point at production endpoints.
Exercise
You load seed data into a scratch org with a data plan. In the plan file, Account is listed first and Contact second. What settings make a Contact's AccountId resolve to the Account created from the first file?
Show answer
Set "saveRefs": true on the Account entry so its reference IDs are saved, and "resolveRefs": true on the Contact entry. In Contact.json, set "AccountId": "@AccountRef1", where AccountRef1 is the referenceId used in Account.json.