How can I get code coverage programatically through Apex?

I’ve looked at the Automated Unit test Execution Recipe and see that it will email the results of running unit tests. I do not see anything in it that gives code coverage results, though. I’d like to be able to run all of the unit tests and get the information that is in the ApexTestResult records (pass/fail, stack, message, etc.) which this recipe does do and also have code coverage results included in the email, which it doesn’t.

I see the ApexClass and ApexTrigger objects, but they don’t have any sort of code coverage field as far as I can tell.

Is there a way to get code coverage results through Apex such as there is way to get test results using ApexTestResults? Preferably the solution would allow me to selectively specify on which classes I want coverage results, but that’s not absolutely necessary.

Answer

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.

Attribution
Source : Link , Question Author : Peter Knolle , Answer Author : Daniel Ballinger

Leave a Comment