Sub topic 18
Testing, debugging and monitoring your automation
This chapter assumes you know the Salesforce data model, can find your way around Setup, and have read the earlier chapters on Flow, Apex triggers, governor limits and the order of execution. You can read simple Apex. Choosing the right tool is only half the job. You also need to prove that the automation works, find the cause when it fails, and notice failures after release.
Why automation needs its own test plan
Automation runs without a person watching. A broken validation rule blocks a user right away. A broken flow or trigger can instead write wrong data for weeks before anyone sees it. Three habits reduce that risk:
- Test the behavior of the whole save, not only one tool in isolation.
- Test with realistic volumes, because many failures only appear in bulk.
- Monitor in production, because test data never covers every real record.
Testing record-triggered flows
Test a record-triggered flow in a sandbox before you deploy it. Use these checks:
- Create or edit a record that meets the entry conditions and confirm the expected result.
- Edit a record that does not meet the entry conditions and confirm that nothing happens.
- Test the "run only when a record is updated to meet the condition requirements" setting. Change an unrelated field on a record that already qualifies, and confirm the flow does not run again.
- Load 200 or more records with Data Loader or an Apex script, and confirm the flow still works.
- Test as a user with a limited profile, since flows can run in different contexts (system context or user context) depending on the setup.
Flow Builder has a Debug button. It runs the flow with a record you pick. You can choose to roll back changes, so the test leaves no data behind. For record-triggered flows, debug runs show each element and the values of variables, which helps you find a wrong decision outcome.
Debug has limits. Without rollback, the changes are saved. Debug also does not replace a bulk test, because it runs one record at a time.
Testing Apex with unit tests
Apex requires tests before code can be deployed to production. The platform requires at least 75% code coverage across your org's Apex. Coverage is a minimum, not a measure of quality. A test can cover every line and still assert nothing.
A good Apex test does four things:
- Creates its own test data. Tests do not see org data by default.
- Exercises the code in bulk, with 200 records.
- Asserts the outcome with
Assertmethods. - Wraps asynchronous code in
Test.startTest()andTest.stopTest().
Here is a test for the AccountTrigger shown earlier in this tutorial. It checks both a matching and a non-matching record in a single bulk insert.
@IsTest
private class AccountTriggerTest {
@IsTest
static void setsHotRatingForLargeAccountsInBulk() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(
Name = 'Test ' + i,
AnnualRevenue = (Math.mod(i, 2) == 0) ? 2000000 : 500
));
}
Test.startTest();
insert accounts;
Test.stopTest();
List<Account> saved = [SELECT Id, AnnualRevenue, Rating FROM Account WHERE Id IN :accounts];
for (Account acc : saved) {
if (acc.AnnualRevenue >= 1000000) {
Assert.areEqual('Hot', acc.Rating, 'Large accounts should be Hot');
} else {
Assert.areNotEqual('Hot', acc.Rating, 'Small accounts should not be Hot');
}
}
}
}Inserting 200 records in one statement is the important part. It runs the trigger once with a full batch, which is the same shape as a Data Loader upload. A trigger that runs a query inside its loop would pass a test with one record and fail here with a governor limit error.
Testing asynchronous Apex
Asynchronous jobs do not run immediately. In a test, jobs queued between Test.startTest() and Test.stopTest() run synchronously when Test.stopTest() is called. Then you can assert on the result. This test covers the RecalculateRatingJob class from the Queueable example.
@IsTest
private class RecalculateRatingJobTest {
@IsTest
static void queueableUpdatesRatings() {
Account big = new Account(Name = 'Big', AnnualRevenue = 5000000);
Account small = new Account(Name = 'Small', AnnualRevenue = 100);
insert new List<Account>{ big, small };
Test.startTest();
System.enqueueJob(new RecalculateRatingJob(new List<Id>{ big.Id, small.Id }));
Test.stopTest();
Assert.areEqual('Hot', [SELECT Rating FROM Account WHERE Id = :big.Id].Rating);
Assert.areEqual('Warm', [SELECT Rating FROM Account WHERE Id = :small.Id].Rating);
}
}> Note that the test data is inserted before Test.startTest(). Setup work should not count against the limits of the code you are measuring.
Testing flows with Apex and flow tests
Salesforce offers flow tests for record-triggered flows. A flow test sets up a record, runs the flow, and checks assertions about the result. You build it in Flow Builder, and it runs in the test framework. Flow tests have limits. They cover record-triggered flows and not screen flows. They also run only in the context of that flow. Because of this, you still need Apex tests or manual tests when several automations act on one object.
Apex tests can also exercise flows indirectly. When a test inserts an Account, any record-triggered flows on Account run as well. This is useful because it tests the combined behavior, as the order-of-execution chapter explained.
Debugging tools
Pick the tool that matches where the failure is.
| Problem | Tool | What it shows |
|---|---|---|
| A flow takes a wrong path | Flow Builder debug | Element-by-element path and variable values |
| A flow failed in production | Flow error email and Paused and Failed Flow Interviews | The failing element and the error message |
| Apex or flow behavior across a full save | Debug log | Order of execution, SOQL and DML counts, limits used |
| Slow or repeated runs | Debug log with limits summary | Queries and CPU time per transaction |
| Failed batch or queueable job | Apex Jobs page | Status, number of errors, and first error text |
Debug logs
A debug log records what happens during a transaction. To capture one, add a trace flag for the user in Setup and set log levels. Then reproduce the problem. Keep the levels as low as you can, since detailed logs grow quickly and can be cut off.
Read a log in this order:
- Find the entry point, such as
CODE_UNIT_STARTEDfor a trigger or flow. - Follow the order of events. You can see before triggers, validation, after triggers and flows in sequence.
- Look at
LIMIT_USAGE_FOR_NSnear the end. It shows how close you came to each governor limit. - Look for
FATAL_ERRORorEXCEPTION_THROWNto find the failure.
Use System.debug() sparingly in Apex. It is useful during development. Leave it out of long-lived code, because it adds noise and costs CPU.
Monitoring in production
Release is the start of monitoring. Use these places regularly:
- Flow error emails. When a flow fails, Salesforce sends an email to the person who last modified the flow. Make sure that address is a monitored mailbox and not a person who has left.
- Paused and Failed Flow Interviews. This Setup page lists failed runs and lets you inspect them.
- Apex Jobs. This page shows queueable, batch and scheduled jobs and their errors.
- Scheduled Jobs. This page confirms that scheduled flows and scheduled Apex are still registered.
- Apex Exception Emails. Setup can send unhandled Apex exceptions to chosen addresses.
- Event Monitoring and limits reports. In larger orgs, these help you spot rising limit use before it causes failures.
Handling errors on purpose
Do not leave failures to chance. For flows, add a fault path from elements that can fail, such as Create Records or Update Records. The fault path can log the error to a custom object or send a notification. Without one, the whole transaction fails and the user sees a generic error.
For Apex, catch only the exceptions you can handle. Use a try/catch around a DML statement to log the failure, and then rethrow or add an error to the record when the user should know. Swallowing an exception silently is worse than failing, since nobody finds out.
public class SafeUpdate {
public static void updateAccounts(List<Account> accounts) {
Database.SaveResult[] results = Database.update(accounts, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
System.debug(LoggingLevel.ERROR,
'Account ' + accounts[i].Id + ' failed: ' + err.getMessage());
}
}
}
}
}Passing false to Database.update allows partial success. Good records are saved, and failures are reported per record. Decide whether partial success is acceptable for your business rule before using it.
A release checklist
Before you release, confirm each item:
- Every Apex class has tests that assert results and use bulk data.
- Every record-triggered flow was tested with matching and non-matching records.
- Fault paths exist on flow elements that write data.
- Error emails go to a monitored address.
- You know where to look when a job or flow fails.
Common mistakes
- Treating 75% coverage as proof of quality.
- Testing with one record and finding limit errors in production.
- Debugging a flow with rollback turned off and leaving test data in the org.
- Leaving debug logs at high detail, so the log is truncated before the failure appears.
- Testing each tool alone and missing a conflict between two automations on the same object.
Exercise
Your record-triggered flow works in Flow Builder debug with one Account, but fails in production when a user imports 5,000 accounts. Name two steps you would take to find and prevent the problem.
Show answer
First, look at the failed run in Paused and Failed Flow Interviews and the error email, and capture a debug log while reproducing a bulk load in a sandbox. The log's limit usage section shows which governor limit was hit. Second, check the flow for Get Records, Update Records or Create Records elements inside a loop, and move them out of the loop so they run once on a collection. Then add a bulk test, with 200 or more records, and add a fault path so future failures are logged.
Exercise
Why must a test for a Queueable class call Test.stopTest() before the assertions?
Show answer
Queued jobs run synchronously when Test.stopTest() is called. Before that point the job has not run, so the assertions would see the unchanged data and fail.