When troubleshooting Apex code coverage, especially during deployments, it can be useful to identify which test classes currently contribute coverage to a specific Apex class or trigger.
Salesforce exposes this information through the Tooling API ApexCodeCoverage object. ApexClassOrTriggerId identifies the class or trigger being tested, while ApexTestClassId identifies the test class generating the coverage. [developer....sforce.com]
1. Get the Apex Class ID
Use the Tooling API to find the target class:
Example:
2. Find Test Classes Providing Coverage
Query ApexCodeCoverage using the class ID:
NumLinesCovered and NumLinesUncovered indicate how much of the target class was exercised by the corresponding test execution. [developer....sforce.com]
3. Return Test Class Names
Instead of working with IDs, include the relationship fields:
Example output:
The same test class may appear multiple times because ApexCodeCoverage can contain multiple coverage records associated with different test executions or methods. TestMethodName can be used to identify the individual method. [developer....sforce.com]
For deployment purposes, extract the unique ApexTestClass.Name values.
4. Check Overall Coverage for the Class
To check aggregate coverage instead of individual contributing tests, query ApexCodeCoverageAggregate:
ApexCodeCoverageAggregate represents aggregate coverage results for an Apex class or trigger. [developer....sforce.com]
Coverage percentage can be calculated as:
Salesforce defines Apex coverage percentage using this covered-lines-to-total-executable-lines calculation. [developer....sforce.com]
Important Distinction
Use:
to answer:
Which test classes exercise this Apex class?
Use:
to answer:
What is the combined coverage of this Apex class?
The ApexCodeCoverage results should be treated as current coverage relationships, not permanent code dependencies. Coverage data reflects tests that have executed and the coverage information currently stored in the org. [developer....sforce.com], [help.salesforce.com]
Deployment Use Case
When an Apex deployment fails due to insufficient coverage:
- Identify the target Apex class ID.
- Query
ApexCodeCoverage. - Extract unique
ApexTestClass.Namevalues. - Review or include the relevant tests in the deployment test configuration.
- Query
ApexCodeCoverageAggregateto verify the resulting class coverage.
This provides a quick way to identify existing tests that exercise a target Apex class before creating additional test classes.
No comments:
Post a Comment