Apex Test Lessons Learned
Overview
This guide distills implementation lessons from real Apex/test-class work where teams had to balance correctness, scale, and maintainability.
It complements generic testing standards with practical decisions that reduced incidents in production.
High-Impact Lessons
1) Test Data Isolation Is Non-Negotiable
- Avoid
SeeAllData=trueexcept highly constrained edge cases. - Build deterministic test data in each test context.
- Use test data factories for consistency and speed.
2) Design for Testability Before Coding Features
- Use interfaces and dependency injection around data/services.
- Isolate DML and callout behavior behind replaceable abstractions.
- Keep orchestration logic separate from integration plumbing.
3) Bulk Tests Must Reflect Real Volume
- Validate behavior with realistic bulk sizes, not only single-record tests.
- Assert no SOQL/DML-in-loop regressions.
- Test async paths with realistic payload sizes.
4) Error-Path Testing Is as Important as Happy Path
- Mock timeouts, 4xx/5xx responses, and malformed payloads.
- Verify retries only for retryable failures.
- Assert log/telemetry behavior on failures.
5) Security Hygiene Includes Test Assets
- Test classes should not be exposed via end-user permission sets.
- Review metadata permissions for accidental test-surface exposure.
Practical Patterns
Pattern: Repository + Service Test Structure
- Service layer contains workflow logic.
- Repository/integration interfaces are injected.
- In-memory test doubles validate interactions.
Pattern: Retry Logic with Guardrails
- Retry only transient failures (lock/contention/network classes).
- Stop early when failure is deterministic (validation/business rule).
- Include governor/resource checks in retry loops.
Pattern: Explainable Scoring or Decision Logic
- Return reason/breakdown structures, not only final scores.
- Tests verify both final decision and decision trace fields.
Anti-Patterns to Avoid
- Massive test methods with multiple unrelated assertions.
- Assertions only on “no exception thrown.”
- Hidden dependencies on org data/config.
- Hardcoded IDs and endpoint strings in tests.
Suggested Test Review Checklist
- Test names describe scenario and expected outcome.
- Positive and negative paths covered.
- Bulk scenarios included where relevant.
- Callout and integration failures tested.
- Security assumptions explicit in tests.
- Flaky timing assumptions removed.
Sources Used
Knowledge/research/topics/apex-test-class-lessons-learned.md- Research-layer implementation lessons and patterns