How to Query Salesforce Code Coverage
Tags: salesforce, codecoverage, query, lightning
Published: 2018-09-18 02:13:32

---
title: How to Query Salesforce Code Coverage
published: true
description: A step by step to query your Salesforce Org's Code Coverage
tags: Salesforce, CodeCoverage, Query, Lightning
cover_image: https://matheusgoncalves.com/wp-content/uploads/2018/09/codeCoverage_Query.jpg
---

In Salesforce Orgs, code coverage percentage is a calculation of the number of covered lines divided by the sum of the number of covered lines and uncovered lines. 

In addition to ensuring the quality of your code, unit tests enable you to meet the code coverage requirements for deploying or packaging Apex. To deploy Apex or package it for the Salesforce AppExchange, unit tests must cover at least 75% of your Apex code, and those tests must pass.

After running tests, you can view code coverage information in the Tests tab of the Developer Console. The code coverage pane includes coverage information for each Apex class and the overall coverage for all Apex code in your organization.

However, you can also use SOQL queries with Tooling API as an alternative way of checking code coverage and a quick way to get more details. Let's see how it works:

<h2>Inspecting Code Coverage</h2>

<h3>Step 1 - Get your org's base URL:</h3>

If you know what's your Org's base URL (<em>you can get it from your browser as well</em>), please jump to step 2.

<ul>
   <li>From Developer Console, open the Debug menu, then select the option "Open Execute Anonymous Window (CTRL+E)
   <li>Enter the following Apex Code:</li>
</ul>

<code>
    String baseURL =  'https://' + System.URL.getSalesforceBaseUrl().getHost();
    System.debug(baseURL);
</code>

<ul>
	<li>Click the button [Execute]</li>

	<li>Go to your Logs tab on the bottom of the page</li>

	<li>Copy the full Base URL, including <em><strong>https://</strong></em></li>

</ul>

<h3>Step 2 - Now you know your base URL, create a Remote Site Setting</h3>

<ul>
	<li>From Setup, enter Remote Site Settings in the Quick Find box, then select Remote Site Settings.</li>

	<li>Click New Remote Site.</li>

	<li>Enter a descriptive term for the Remote Site Name.</li>

	<li>Enter the URL for the remote site.</li>

	<li>Optionally, enter a description of the site.</li>

</ul>

<img src="https://matheusgoncalves.com/wp-content/uploads/2018/09/Screen-Shot-2018-09-17-at-10.13.45-AM.png" alt="" width="704" height="296" class="aligncenter size-full wp-image-682" />

<ul>
	<li>Click Save.</li>

	<li>Just in case, create a second Remote Site Settings for the URL in the "Visual.force.com" format:
            <ul><li>https://c.<strong>xx99</strong>.visual.force.com - where xx99 is the code of your org's instance.</li></ul>
        </li>

</ul>


<h3>Step 3 - Get the JSON file for the Code Coverage Wrapper</h3>

<ul>
	<li>Go back to the Developer Console, open the Debug menu, then select the option "Open Execute Anonymous Window (CTRL+E)</li>
	<li>Enter the following Apex Code:</li>

</ul>

{% gist https://gist.github.com/gitmatheus/cfa4066d666e6000a40c5b5ff88cc73b %}


<ul>
<li>Click the button [Execute]</li>
<li>Go to your Logs tab on the bottom of the page</li>
<li>Copy the full JSON result</li>
  <ul><li>Please note you will need to remove any text before the first <strong>"{"</strong> bracket. </li>
      <li>Eg.: "<em>hh:mm:ss:999 USER_DEBUG [99]|DEBUG|</em>"</li>
  </ul>
<li>Go to the website JSON2Apex: <a href="https://json2apex.herokuapp.com/" rel="noopener" target="_blank">https://json2apex.herokuapp.com/</a></li>
<li>Paste your JSON file</li>
<li>Enter the name for the generated class (here, we will use <strong>CodeCoverageWrapper</strong>)</li>
<li>Click the button <strong>[Create Apex]</strong> </li>
</ul>

<img src="https://matheusgoncalves.com/wp-content/uploads/2018/09/Screen-Shot-2018-09-17-at-3.50.04-PM.png" alt="" width="1215" height="863" class="aligncenter size-full wp-image-689" />

<ul>
<li>Download the generated zip file that contains the Wrapper class plus the Test class.</li>
<li>Extract the files</li>
<li>Open the files with your prefered text editor</li>
<li>Check if everything looks good, and add these classes to your Salesforce org as new classes.</li>
</ul>

This is how it looks like: 

{% gist https://gist.github.com/gitmatheus/259b94489c96c2526aed90ccece4aeee %}


<h3>Step 4 - Create a Helper Class</h3> 

<ul>
	<li>Create the following class, that contains a method that will query and return information about the Code Coverage</li>
</ul>

{% gist https://gist.github.com/gitmatheus/bac6cbf1113218ef30f12dc27ed970d3 %}


<strong>Don't forget to write the test class for it. </strong>

<h3>Step 5 - Create a Controller and a Page to display the Code Coverage</h3>

<ul><li>Create the following class, that contains the logic for the page</li></ul>

{% gist https://gist.github.com/gitmatheus/9c787bc979db18e71750decf0a21bd16 %}


Create the following page, using the controller we just created.

Please note we're leveraging <strong><a href="https://www.lightningdesignsystem.com/getting-started/" rel="noopener" target="_blank">Salesforce Lightning Design System</a></strong>;


{% gist https://gist.github.com/gitmatheus/8bc84beac4706fabc2ebc8c949f43903 %}


The page has two buttons. One to sort the results by Class / Trigger name, and another button to sort the results by Code Coverage.

This is how it looks like: 

<img src="https://matheusgoncalves.com/wp-content/uploads/2018/09/Screen-Shot-2018-09-17-at-4.28.28-PM.png" alt="" width="795" height="293" class="aligncenter size-full wp-image-705" />

<img src="https://matheusgoncalves.com/wp-content/uploads/2018/09/Screen-Shot-2018-09-17-at-4.30.06-PM.png" alt="" width="796" height="297" class="aligncenter size-full wp-image-706" />

<h2>Final Considerations</h2>

You can follow the same logic to use the Tooling API whenever you need to query exposed metadata used in developer tooling that you can access through REST or SOAP. 

Also, the method <em><strong>sortCodeCoverageMapByCoverage</strong></em> from <em><strong>CodeCoverageHelper</strong></em> is quite handy and can be used as an example for situations when you need to sort Maps by its values. In this case, sort the Code Coverage percentage value. 

Just don't forget to adapt the Wrapper and the Comparable.

You can find all code used for this project in my GitHub account, at <a href="https://github.com/gitmatheus/QueryCodeCoverage" rel="noopener" target="_blank">github.com/gitmatheus/QueryCodeCoverage</a>

{% github toadgeek/QueryCodeCoverage %}

I hope you enjoyed the ride and learned something new today. 

See you next time.

*This article was originally posted at [matheus.dev](https://matheus.dev/how-to-query-salesforce-code-coverage/)*