Tutorial: use Apex AI to generate and refine Apex test classes to boost Salesforce test coverage quickly for new or legacy Apex code.
Shipping Salesforce changes often fails for one reason: test coverage. Whether you’re introducing a new Apex class or inheriting a legacy codebase with thin or brittle tests, Apex AI can help you generate solid Apex test classes quickly-without losing engineering control.
## What you’ll accomplish in this tutorial
In this “use this application” tutorial, you’ll use Apex AI to:
- Generate an Apex test class for a target Apex class (new or existing)
- Validate compilation and coverage in your org/CI
- Iterate to handle common failures (data setup, sharing, async)
- Produce a reliable test suite that’s ready for pull requests
## Prerequisites
Before you start, make sure you have:
- The Apex class (or trigger handler) you need coverage for
- Access to your Salesforce org or scratch org for test execution
- A clear list of dependencies (custom objects, fields, record types, flows/processes) that may impact behavior
## Step 1: Choose a target class and define success criteria
Pick a single Apex class to start. For the fastest results, start with a class that:
- Has clear entry points (public methods)
- Uses minimal dynamic SOQL or complex integration behavior
Define your goal up front:
- Coverage threshold (e.g., org-wide 75% and class-level 85%+)
- Required assertions (not just executing lines)
- Deterministic outcomes (tests should pass consistently in CI)
## Step 2: Generate a test class in Apex AI
Open Apex AI and point it at the class you want to cover. Provide the minimal context needed for accurate generation:
- The Apex class code (and any helper classes it depends on)
- Object/field details referenced by the class
- Expected behavior for key scenarios (happy path + 1–2 edge cases)
Apex AI will produce a test class structure that typically includes:
- @TestSetup data creation for stable, reusable records
- Positive and negative test methods
- Assertions aligned to business logic (DML results, status changes, exceptions)
### Tip: Ask for scenario-based tests, not just “increase coverage”
If you’re using a prompt or generation options, request tests that cover:
- Null/blank inputs
- Permission/sharing constraints (if applicable)
- Boundary values for numeric/date fields
## Step 3: Run tests and address the first failure
Deploy or add the generated test class to your project and run it (VS Code, SFDX, DevOps pipeline, or Setup UI).
When failures happen, they’re usually in one of these buckets:
- **Data issues**: missing required fields, validation rules, record types
- **Automation side effects**: flows, workflow, triggers altering expected results
- **Sharing/FLS**: “insufficient access” or unexpected visibility behavior
- **Async behavior**: queueables/futures/batch jobs requiring Test.startTest/stopTest
## Step 4: Iterate with Apex AI using failure feedback
Paste the exact error message and stack trace back into Apex AI, along with any relevant org constraints (validation rules, required lookups, automation notes).
Common adjustments you can request:
- Update @TestSetup to create compliant data that satisfies validations
- Add RunAs users/roles when testing sharing-sensitive logic
- Wrap async execution with Test.startTest() and Test.stopTest()
- Add stubs/mocks for callouts (HttpCalloutMock) if integrations exist
### Tip: Lock in determinism
If tests pass locally but fail in CI, ask Apex AI to:
- Avoid relying on existing org data (no SeeAllData=true)
- Remove time-dependent logic (use fixed Date/Datetime)
- Use explicit assertions rather than “assert not null” placeholders
## Step 5: Finalize: quality checks before merging
Before you open a PR, ensure the generated tests:
- Contain meaningful assertions for each scenario
- Use @TestSetup appropriately to minimize test time
- Cover exception paths where business logic requires it
- Are readable and aligned with your team’s naming conventions
## Conclusion
Apex AI is most valuable when you treat it as an accelerator for reliable coverage-not a black box. Use it to generate a strong first draft, run tests, feed back failures, and iterate until your suite is stable in CI. Ready to eliminate coverage bottlenecks? Use Apex AI on your next Apex class and ship faster with confidence.