Stop flaky Apex tests. Use mocking, dependency injection, deterministic test data, and isolation patterns to make Salesforce test suites reliable and fast.
## Why flakiness hurts code quality
Flaky tests erode confidence in your CI pipeline, obscure real regressions, and waste developer time chasing nondeterministic failures. For Salesforce teams, Apex test instability slows deployments and reduces the value of automated testing.
### Common causes of flaky Apex tests
- Environment and org data dependencies (SeeAllData=true)
- Time-sensitive logic (relative dates, system time)
- External callouts and intermittent integrations
- Race conditions with asynchronous jobs
- Tests that modify global state or rely on implicit ordering
## Practical strategies to make Apex tests deterministic
Below are concrete, actionable techniques you can apply immediately to reduce flakiness and improve code quality.
### 1. Isolate tests from org data
Always use @isTest(seeAllData=false) for new tests. Build test data with factories or Test.loadData to ensure each test has the exact records it needs. Avoid querying Common objects assuming they exist in every org.
### 2. Use mocking and stubbing for callouts and integrations
Replace real HTTP or SOAP calls with mocks. Use Test.setMock(HttpCalloutMock.class, mock) for callouts, or the Stub API (System.Test.createStub) for interfaces. Mock responses should be deterministic and cover edge conditions explicitly.
### 3. Apply dependency injection
Design services and utility classes to accept dependencies (e.g., connectors, clock, repositories) via constructor or setter injection. In tests, inject fakes or stubs so logic is exercised without relying on external systems.
### 4. Control time and randomness
Avoid using System.now() or Math.random() directly in business logic. Inject a clock interface or pass explicit timestamps into methods. Where randomness is required, seed the generator or inject a predictable pseudo-random provider.
### 5. Stabilize async behavior
Use Test.startTest()/Test.stopTest() to force asynchronous work to finish during tests. For batch, queueable, and future patterns, verify post-stopTest outcomes instead of assuming timing. Where possible, extract processing into synchronous helper methods that can be exercised directly.
### 6. Keep tests small, focused, and independent
A test should validate one behavior. Reset or avoid global state and feature flags that cross-test boundaries. This reduces accidental coupling and makes failures easier to diagnose.
### 7. Build a lightweight test data factory
Centralize test record creation in a factory that returns minimal, valid SObjects. Factories make it easy to change fields consistently, reduce duplication, and speed test setup.
## Measuring improvement
Track flaky test rate over time in your CI reports. Define thresholds for acceptable failure rates and require triage of nondeterministic failures the same day they occur.
Conclusion / Call-to-action
Deterministic tests are a high-leverage investment: they increase deployment velocity and maintain developer trust in automation. Start by introducing mocking and a test data factory this sprint, and measure flakiness before and after. If you want help generating robust Apex tests or automating test factories, try Test Class Generator to accelerate and standardize test coverage across your org.