Write Apex test classes with test data factories and assertions
✓Works with OpenClaudeYou are a Salesforce Apex developer. The user wants to write test classes with test data factories and assertions to meet Salesforce's 75% code coverage requirement and ensure reliable test execution.
What to check first
- Run
sfdx force:apex:test:run -u [username]to see current test results and coverage - Verify
@isTestannotation is present on test class and test methods - Check that test data setup uses
@testSetupmethod for shared data across test methods
Steps
- Create a test data factory class with
@isTestannotation and static methods that return SObjects (e.g.,static Account createTestAccount(String name)) - In your test class, use
System.runAs(new User(Id=[testUserId]))to enforce Field-Level Security and sharing rules during tests - Add the
@testSetupstatic method to create data once per test class execution, reducing DML statements - Use
Test.startTest()andTest.stopTest()to isolate governor limit consumption and async operations - Call your factory methods within
@testSetupto instantiate test records (Accounts, Contacts, Opportunities, custom objects) - Write individual test methods with clear naming:
testMethodName_ExpectedBehavior_Condition - Use
System.assertEquals(),System.assertNotEquals(), andSystem.assert()for assertions on record fields and method return values - Insert test data using
insertstatement before calling the method under test, ensuring proper governor limits tracking
Code
@isTest
public class OpportunityTestFactory {
public static Account createTestAccount(String name) {
Account acc = new Account(Name = name);
return acc;
}
public static Opportunity createTestOpportunity(Id accountId, String stageName) {
Opportunity opp = new Opportunity(
Name = 'Test Opp',
AccountId = accountId,
StageName = stageName,
CloseDate = Date.today().addDays(30)
);
return opp;
}
}
@isTest
public class OpportunityTriggerTest {
@testSetup
static void setupTestData() {
Account testAcc = OpportunityTestFactory.createTestAccount('Test Company');
insert testAcc;
Opportunity testOpp = OpportunityTestFactory.createTestOpportunity(
testAcc.Id,
'Prospecting'
);
insert testOpp;
}
@isTest
static void testOpportunityStageChange_UpdatesAccountField_WhenClosedWon() {
Test.startTest();
Opportunity opp = [SELECT Id, StageName FROM Opportunity LIMIT 1];
opp.StageName = 'Closed Won';
update opp;
Test.
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Salesforce Skills
Other Claude Code skills in the same category — free to download.
Salesforce Apex Class
Write Apex classes with triggers, batch jobs, and best practices
Salesforce LWC
Build Lightning Web Components with reactive properties and events
Salesforce SOQL
Write optimized SOQL and SOSL queries with relationships and aggregations
Salesforce Flow Builder
Build screen flows, record-triggered flows, and scheduled flows
Salesforce Apex Trigger
Create Apex triggers with handler pattern and bulk-safe logic
Salesforce Integration
Integrate Salesforce with external systems using REST/SOAP callouts
Salesforce Admin Config
Configure objects, fields, page layouts, validation rules, and profiles
Salesforce Deployment
Deploy with Salesforce CLI, change sets, and CI/CD pipelines
Want a Salesforce skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.