Test Reports

Like all Apex code, Salesforce Reports and Dashboards API via Apex code requires test coverage.

The Reporting Apex methods don’t run in system mode, they run in the context of the current user (also called the context user or the logged-in user). The methods have access to whatever the current user has access to.

In Apex tests, report runs always ignore the SeeAllData annotation, regardless of whether the annotation is set to true or false. This means that report results will include pre-existing data that the test didn’t create. There is no way to disable the SeeAllData annotation for a report execution. To limit results, use a filter on the report.

Records inserted during the test method aren’t guaranteed to appear in the report results, even though report runs ignore the SeeAllData annotation. To limit report results reliably, use a filter, not a record count.

The following example tests asynchronous and synchronous reports. This sample assumes you have created and saved a report with the Developer Name Closed_Sales_This_Quarter. Each method:

  • Creates a new Opportunity object and uses it to set a filter on the report.
  • Runs the report.
  • Calls assertions to validate the data.

In Apex tests, asynchronous reports execute only after the test is stopped using the Test.stopTest method. Test.stopTest flushes asynchronous work only in the current test method. A helper method that later calls Reports.ReportManager.getReportInstance doesn’t rerun the report. Always check getStatus() before you call getReportResults(). If the status is Error, the instance finished unsuccessfully—that’s a status value, not an Apex exception.