How can I get code coverage programatically through Apex?

For synchronous testing: The RunTestsResult returned by calling ApexService.runTests() contains a codeCoverage property, which is a CodeCoverageResult array.

The CodeCoverageResult locationsNotCovered property gives you the line number and column of code that wasn't tested in the run.

My experience with this is that it will return code coverage results for any class that gets touched by the test case(s) and you don't get any control over it. Also, it isn't a cumulative view of the code coverage, only what is covered by that specific test run. So you can get lots of results indicating very low code coverage for classes that weren't being targeted by the test cases in the run but might otherwise have really good coverage.


Internally Salesforce appear to be tracking the results of previous tests runs. The Code coverage page https://na2.salesforce.com/setup/build/viewCodeCoverage.apexp?id=01p400000000XYZ has that drop box at the top that can toggle between previous run results. Sadly I've never been able to query this data programmatically. You can access this data via the Tooling API and the ApexCodeCoverage records.

Tags:

Apex

Unit Test