Sub topic 8
Testing and Deployment Compared
This chapter compares how Apex and Flow are tested and moved between environments. It assumes you know the Salesforce data model, can navigate Setup, have built a simple flow, and understand variables, loops, and collections. Earlier chapters covered what each tool is and how governor limits and bulk-safe design apply. Here the focus is on proving that automation works and getting it to production safely.
Why testing and deployment shape the choice
Both tools change data in production, so both need verification before release. The platform enforces this differently for each. Apex has a hard, enforced gate. Flow has a softer gate that relies on team discipline. That difference affects cost, risk, and how fast you can ship.
| Aspect | Apex | Flow |
|---|---|---|
| Test authoring | Written as Apex test classes | Debug tool, optional flow tests, manual checks |
| Required for production deploy | Yes, 75% overall code coverage | No coverage rule for flows |
| Where changes can be made | Sandbox or scratch org, or developer tools; not directly in production | Flow Builder, including production (if permitted) |
| Version control | Plain-text files, easy to diff | Metadata XML, harder to read in diffs |
| Rollback | Deploy the previous version | Activate a previous flow version |
How Apex is tested
Apex tests are Apex classes marked with @IsTest. Each test method sets up its own data, runs the code under test, and checks results with assertions. Tests run in an isolated context. Any records a test inserts are rolled back when it finishes, and by default tests cannot see existing org data.
The test below inserts 200 contacts in one operation. That is the maximum batch size a trigger handles in one chunk, so it checks the bulk behavior from the earlier chapter.
@IsTest
private class ContactTriggerTest {
@IsTest
static void countsContactsInBulk() {
Account a = new Account(Name = 'Acme');
insert a;
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) {
contacts.add(new Contact(LastName = 'Contact ' + i, AccountId = a.Id));
}
insert contacts;
a = [SELECT Contact_Count__c FROM Account WHERE Id = :a.Id];
Assert.areEqual(200, a.Contact_Count__c);
}
}The test assumes the custom number field Contact_Count__c exists on Account, and that the ContactTrigger from the bulkification chapter is deployed. The final line uses the Assert class. A test with no assertions can still raise coverage, but it proves nothing.
The 75% coverage rule
Deploying Apex to production requires at least 75% overall code coverage across the org's Apex, and every trigger must have some coverage. Coverage is the share of executable lines that ran during tests. Four points matter in practice:
- The rule applies to the whole org, not to each class. One poorly tested class can be hidden by well-tested ones, but it will still bite you later.
- Coverage measures lines executed, not behavior verified. Treat 75% as a floor, not a goal.
- Tests that fail block deployment, even when coverage is high.
- Test data should be created in the test. Relying on existing org data makes tests fail when deployed to an environment with different data.
What to test
A useful Apex test suite covers more than the happy path:
- Bulk behavior. Run with 200 records, as in the example above, to catch queries or DML inside loops.
- Negative cases. Insert records that should be skipped, such as contacts with no account, and confirm nothing breaks.
- Permissions. Use
System.runAs()with a user that has a specific profile or permission set when the code depends on sharing or field access. - Error paths. Confirm that expected exceptions or validation failures occur when they should.
Use Test.startTest() and Test.stopTest() around the code under test when it uses asynchronous Apex such as Queueable or Batch jobs. Calling Test.stopTest() forces queued async work to finish before your assertions run. These calls also give the code under test a fresh set of governor limits, separate from the limits used by test setup.
How Flow is tested
Flow has no coverage requirement, but it does have testing tools. You have three main options.
- Debug in Flow Builder. You run the flow with chosen input values or a chosen record, and you see which path it took and what each element did. You can run it with rollback turned on so no data is saved. This is quick and useful during building, but it is manual and not repeatable by a pipeline.
- Flow tests. For record-triggered flows, you can define a test that sets up record values, runs the flow, and checks assertions about the outcome. These tests can be run again whenever you change the flow. They cover less ground than Apex tests. Flow tests are intended for single-record scenarios and do not exercise bulk behavior with hundreds of records.
- Manual and scripted tests in a sandbox. Create or update real records and check the results. For bulk checks, load a file of many records with Data Loader or Data Import Wizard, then inspect the outcome.
The gap that matters
Because no tool forces a bulk test, a flow can pass every debug run and still hit limits when a user loads 5,000 records. The platform makes Apex authors prove the code runs. It does not make flow authors prove it. If your flow is record-triggered on an object that receives bulk loads, add a bulk test to your own checklist.
How Apex is deployed
Apex code is metadata stored in text files, such as ContactTrigger.trigger and ContactTriggerTest.cls. You cannot edit Apex directly in a production org through the normal tools. The standard path is:
- Write the code and tests in a sandbox or scratch org.
- Run the tests there and fix failures.
- Deploy to production using a change set, the Salesforce CLI, or a CI/CD pipeline.
- During deployment, Salesforce runs tests and enforces coverage.
Production deploys run tests by default. You can validate a deployment first, which runs the tests without saving the changes, and then do a quick deploy once validation has passed. This shortens the release window.
sf project deploy start --source-dir force-app --test-level RunLocalTests --target-org prodThe RunLocalTests level runs all tests in your org except those from installed managed packages. It is the level most teams use for production.
The files are plain text, so version control works well. Reviewers see line-by-line differences, and a pull request can show exactly what changed.
How Flow is deployed
A flow is also metadata, stored as XML. It moves through the same tools: change sets, the Salesforce CLI, and pipelines. Two differences matter.
- No coverage gate. Salesforce does not run flow tests as part of deployment unless you ask for that. A broken flow can be deployed without any failure from the platform. Flow tests can be included in a deploy and run, but you must set that up.
- Versions and activation. Each save of a flow creates a version, and only one version is active at a time. Deploying a flow can bring over an inactive version, which you then activate. This gives a quick rollback path: reactivate the previous version.
Flow XML is verbose, and a small change in the canvas can reorder elements and produce a large diff. Reviewing flow changes in version control is harder than reviewing Apex. Teams often compensate with naming conventions, descriptions on each element, and screenshots in change requests.
Rollback and recovery
Apex rollback means deploying the earlier code again. That needs the old version in source control, and the deploy runs the full test cycle again. For urgent fixes, a trigger can be disabled by deploying it as inactive, which is faster than writing new logic.
Flow rollback is quicker. In Flow Builder, you open the flow, pick the previous version, and activate it. No deploy is needed if you have permission in production. The trade-off is that this is easy to do without review, so restrict who can activate flows in production.
Neither rollback undoes data changes already made. If automation updated 10,000 records incorrectly, you need a data fix, such as a report-based export and reload. Design for this by testing in a sandbox with realistic data volumes.
Common errors
- Tests depend on org data. An Apex test that queries existing records passes in a full sandbox and fails in production or a scratch org. Create the data in the test.
- Coverage without assertions. Tests that only call methods raise coverage but do not catch regressions.
- Hard-coded IDs. Record IDs differ between orgs. Query by name or developer name, or create the record in the test. The same applies to flows that reference IDs directly.
- Activating a flow straight in production. It skips the sandbox bulk test and review.
- Forgetting that tests share limits. In Apex, setup and test code share limits unless you use
Test.startTest(), which can lead to confusing limit failures in tests. - Ignoring flow dependencies. A flow that calls an Apex invocable method fails if the Apex class is missing in the target org. Deploy both together. The next chapters on hybrid designs return to this.
Decision criteria for this topic
Testing and deployment should influence your choice when:
- Your team already has a CI/CD pipeline with automated tests. Apex fits in more naturally.
- The logic is complex enough that you need many test cases. Apex tests are easier to write and run in volume than flow tests.
- Admins need to ship small changes quickly with simple review. Flow's versioning and activation model suits this, as long as you add your own bulk testing step.
- The change is high risk, such as financial calculations. The enforced tests and readable diffs of Apex lower risk.
Exercise
A team deploys a record-triggered flow to production after it passes every debug run with a single record. A week later, a data load of 5,000 records fails partway through with a limit error. Why did the platform not catch this before deployment, and what should the team add to its process?
Show answer
Salesforce does not require tests or coverage for flows, so nothing forced a bulk test, and debug runs use one record at a time. The team should add a bulk test in a sandbox, loading a few hundred or thousand records with Data Loader before activation. They should also consider flow tests for the main paths, and move the logic to Apex or reduce per-record operations if the flow cannot stay inside governor limits.
Exercise
Your Apex trigger has 80% overall coverage in the org and all tests pass, but one test class has no assertions. Can you deploy to production, and should you?
Show answer
You can deploy, because the org meets the 75% overall coverage rule and the tests pass. You should not stop there. A test without assertions only runs lines and does not verify behavior, so regressions can slip through. Add assertions, such as checking the field values after an insert of 200 records.