Skip to content

forcedotcom/sf-skills / plugins/builder/salesforce-development/skills/platform-data-manage

platform-data-manage

Verified

Salesforce data operations with 130-point scoring. Use to create, update, delete, bulk import/export, generate test data, and clean up org records via sf CLI and anonymous Apex. TRIGGER on creating test data, bulk import/export, sf data CLI commands, data-factory patterns for Apex tests, or seeding/cleaning org records. DO NOT TRIGGER for SOQL query writing only (use platform-soql-query), Apex test execution (use platform-apex-test-run), or metadata deployment (use platform-metadata-deploy).

FileKindSize
README.mdmarkdown4.5 KB
SKILL.mdskill md10.5 KB
assets/bulk/bulk-insert-10000.apexother12.3 KB
assets/bulk/bulk-insert-200.apexother12.4 KB
assets/bulk/bulk-insert-500.apexother13.1 KB
assets/bulk/bulk-upsert-external-id.apexother13.4 KB
assets/cleanup/delete-by-created-date.apexother15.9 KB
assets/cleanup/delete-by-name.apexother12.9 KB
assets/cleanup/delete-test-data.apexother16.6 KB
assets/cleanup/rollback-transaction.apexother12.4 KB
assets/csv/account-import.csvother1.8 KB
assets/csv/contact-import.csvother1.9 KB
assets/csv/custom-object-import.csvother1.1 KB
assets/csv/opportunity-import.csvother1.6 KB
assets/factories/account-factory.apexother5.6 KB
assets/factories/case-factory.apexother8.1 KB
assets/factories/contact-factory.apexother5.9 KB
assets/factories/custom-object-factory.apexother10.8 KB
assets/factories/event-factory.apexother9.6 KB
assets/factories/hierarchy-factory.apexother16.0 KB
assets/factories/lead-factory.apexother6.4 KB
assets/factories/opportunity-factory.apexother7.3 KB
assets/factories/task-factory.apexother8.1 KB
assets/factories/user-factory.apexother8.8 KB
assets/json/account-contact-tree.jsonconfig3.6 KB
assets/json/account-opportunity-tree.jsonconfig3.3 KB
assets/json/full-hierarchy-tree.jsonconfig5.8 KB
assets/soql/aggregate.soqlother12.3 KB
assets/soql/child-to-parent.soqlother9.8 KB
assets/soql/parent-to-child.soqlother8.6 KB
assets/soql/polymorphic.soqlother11.1 KB
assets/soql/subquery.soqlother16.2 KB
references/anonymous-apex-guide.mdmarkdown2.0 KB
references/bulk-operations-guide.mdmarkdown1.8 KB
references/bulk-testing-example.mdmarkdown4.9 KB
references/cleanup-rollback-example.mdmarkdown8.2 KB
references/cleanup-rollback-guide.mdmarkdown1.7 KB
references/crud-workflow-example.mdmarkdown4.0 KB
references/governor-limits-reference.mdmarkdown1.8 KB
references/orchestration.mdmarkdown7.0 KB
references/relationship-query-examples.mdmarkdown5.7 KB
references/sf-cli-data-commands.mdmarkdown2.8 KB
references/soql-relationship-guide.mdmarkdown2.0 KB
references/test-data-best-practices.mdmarkdown3.2 KB
references/test-data-factory-usage.mdmarkdown7.6 KB
references/test-data-patterns.mdmarkdown2.4 KB
scripts/soql_validator.pyscript10.9 KB
scripts/validate_data_operation.pyscript13.5 KB

references/test-data-factory-usage.md

View on GitHub
<!-- Parent: platform-data-manage/SKILL.md -->
# Test Data Factory Usage

How to use and customize the test data factory templates.

## Basic Factory Pattern

### Account Factory
```apex
public class TestDataFactory_Account {

    // Basic creation - inserted
    public static List<Account> create(Integer count) {
        return create(count, true);
    }

    // Control insertion
    public static List<Account> create(Integer count, Boolean doInsert) {
        List<Account> records = new List<Account>();
        for (Integer i = 0; i < count; i++) {
            records.add(new Account(
                Name = 'Test Account ' + i,
                Industry = 'Technology'
            ));
        }
        if (doInsert) {
            insert records;
        }
        return records;
    }
}
```

### Usage Examples

```apex
// Create 10 accounts (inserted)
List<Account> accounts = TestDataFactory_Account.create(10);

// Create 10 accounts (not inserted - for customization)
List<Account> accounts = TestDataFactory_Account.create(10, false);
accounts[0].AnnualRevenue = 1000000;
accounts[1].Rating = 'Hot';
insert accounts;
```

## Factory with Variations

### Industry Variations
```apex
public static List<Account> createWithVariedIndustries(Integer count) {
    List<Account> records = new List<Account>();
    List<String> industries = new List<String>{
        'Technology', 'Healthcare', 'Finance', 'Manufacturing', 'Retail'
    };

    for (Integer i = 0; i < count; i++) {
        records.add(new Account(
            Name = 'Test Account ' + i,
            Industry = industries[Math.mod(i, industries.size())]
        ));
    }
    insert records;
    return records;
}
```

### Revenue Tiers
```apex
public static List<Account> createWithRevenueTiers(Integer count) {
    List<Account> records = new List<Account>();
    List<Decimal> tiers = new List<Decimal>{
        100000, 500000, 1000000, 5000000, 10000000
    };

    for (Integer i = 0; i < count; i++) {
        records.add(new Account(
            Name = 'Test Account ' + i,
            AnnualRevenue = tiers[Math.mod(i, tiers.size())]
        ));
    }
    insert records;
    return records;
}
```

## Factory with Relationships

### Contact Factory with Account
```apex
public class TestDataFactory_Contact {

    // Create contacts for existing accounts
    public static List<Contact> createForAccounts(Set<Id> accountIds, Integer perAccount) {
        List<Contact> contacts = new List<Contact>();
        Integer i = 0;

        for (Id accId : accountIds) {
            for (Integer j = 0; j < perAccount; j++) {
                contacts.add(new Contact(
                    FirstName = 'Test',
                    LastName = 'Contact ' + i,
                    AccountId = accId,
                    Email = 'test' + i + '@example.com'
                ));
                i++;
            }
        }
        insert contacts;
        return contacts;
    }
}
```

### Usage
```apex
// Create 10 accounts with 3 contacts each
List<Account> accounts = TestDataFactory_Account.create(10);
Set<Id> accountIds = new Map<Id, Account>(accounts).keySet();
List<Contact> contacts = TestDataFactory_Contact.createForAccounts(accountIds, 3);
// Total: 10 accounts + 30 contacts
```

## Hierarchy Factory

### Complete Hierarchy in One Call
```apex
public class TestDataFactory_Hierarchy {

    public class HierarchyResult {
        public List<Account> accounts;
        public List<Contact> contacts;
        public List<Opportunity> opportunities;
    }

    public static HierarchyResult create(
        Integer accountCount,
        Integer contactsPerAccount,
        Integer oppsPerAccount
    ) {
        HierarchyResult result = new HierarchyResult();

        // Create accounts
        result.accounts = TestDataFactory_Account.create(accountCount);
        Set<Id> accountIds = new Map<Id, Account>(result.accounts).keySet();

        // Create contacts
        result.contacts = TestDataFactory_Contact.createForAccounts(
            accountIds, contactsPerAccount
        );

        // Create opportunities
        result.opportunities = TestDataFactory_Opportunity.createForAccounts(
            accountIds, oppsPerAccount
        );

        return result;
    }
}
```

### Usage
```apex
// Create complete test hierarchy
HierarchyResult data = TestDataFactory_Hierarchy.create(
    10,  // accounts
    3,   // contacts per account
    2    // opportunities per account
);
// Total: 10 accounts + 30 contacts + 20 opportunities

System.debug('Accounts: ' + data.accounts.size());
System.debug('Contacts: ' + data.contacts.size());
System.debug('Opportunities: ' + data.opportunities.size());
```

## Edge Case Factories

### Boundary Values
```apex
public static Account createWithMinValues() {
    return new Account(
        Name = 'A'  // Minimum name length
    );
}

public static Account createWithMaxValues() {
    return new Account(
        Name = 'X'.repeat(255),  // Maximum name length
        Description = 'Y'.repeat(32000)  // Maximum description
    );
}
```

### Special Characters
```apex
public static Account createWithSpecialCharacters() {
    return new Account(
        Name = 'Test & "Special" <Characters> \'Quotes\''
    );
}
```

### Null/Empty Values
```apex
public static List<Account> createWithNullableFields(Integer count) {
    List<Account> records = new List<Account>();
    for (Integer i = 0; i < count; i++) {
        Account acc = new Account(Name = 'Test ' + i);
        // Leave optional fields null
        // acc.Industry = null;
        // acc.AnnualRevenue = null;
        records.add(acc);
    }
    insert records;
    return records;
}
```

## Using Factories for Testing

### Trigger Test Example
```apex
@isTest
public class AccountTriggerTest {

    @isTest
    static void testBulkInsert() {
        // Setup - 201 records to test batch boundaries
        Test.startTest();
        List<Account> accounts = TestDataFactory_Account.create(201);
        Test.stopTest();

        // Verify trigger logic executed
        List<Account> results = [
            SELECT Id, Custom_Field__c
            FROM Account
            WHERE Id IN :accounts
        ];

        for (Account acc : results) {
            System.assertNotEquals(null, acc.Custom_Field__c,
                'Trigger should have set Custom_Field__c');
        }
    }

    @isTest
    static void testWithRelatedRecords() {
        // Setup hierarchy
        HierarchyResult data = TestDataFactory_Hierarchy.create(5, 2, 1);

        Test.startTest();
        // Test logic that involves relationships
        MyClass.processAccountsWithContacts(data.accounts);
        Test.stopTest();

        // Verify results
    }
}
```

### Flow Test Example
```apex
@isTest
static void testRecordTriggeredFlow() {
    // Create data that matches flow entry criteria
    List<Account> accounts = TestDataFactory_Account.create(10, false);
    for (Account acc : accounts) {
        acc.Industry = 'Technology';  // Matches flow filter
        acc.AnnualRevenue = 1000000;  // Triggers flow action
    }

    Test.startTest();
    insert accounts;  // Flow fires on insert
    Test.stopTest();

    // Verify flow results
    List<Task> tasks = [SELECT Id FROM Task WHERE WhatId IN :accounts];
    System.assertEquals(10, tasks.size(), 'Flow should create task for each account');
}
```

## Best Practices

1. **Always return inserted records** - Caller may need IDs
2. **Provide doInsert parameter** - Allow customization before insert
3. **Use bulk patterns** - Single DML for multiple records
4. **Handle required fields** - Prevent validation errors
5. **Use unique values** - Avoid duplicate rule violations
6. **Track IDs for cleanup** - Enable proper test isolation
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 322kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 322kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 322kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 198kUpdated Claude CodeCodexVerifiedInstall