Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    • How to Use Graph API for Outlook-Salesforce Connection
    • Enhancing Performance with File Compression in Apex
    • Salesforce Spring ’25 Release: Top Flow Enhancements You Need to Know
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Thursday, May 8
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»Apex»Apex Code Coverage In Custom Object

    Apex Code Coverage In Custom Object

    Dhanik Lal SahniBy Dhanik Lal SahniMay 17, 2021Updated:June 11, 20232 Comments4 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Apex Code Coverage In Custom Object
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Apex code coverage is important when we move code from one Sandbox to other or production environment. In sandbox environment, we can move code without minimum code coverage but for production, we need minimum 75% code coverage for custom apex code.

    Checking Org’s Apex Code Coverage:

    We can check code coverage using Apex class screen.

    Apex Code Coverage
    Apex Code Coverage

    Checking Individual Apex Class Code Coverage:

    We can check individual apex code class coverage from Developer console by running test class. It will give result with code coverage percentage with each class.

    We can check this report on screen but we can not export or save this code coverage report.

    How to get Code Coverage using Tooling API?

    We can get code coverage of custom code using Tooling API. Below Tooling API object will help us in getting code coverage for apex and trigger.

    ApexCodeCoverage – This object will give code coverage test results for an Apex class or trigger. This will show individual method code coverage for each class. If same class is executed from multiple places, it will show coverage based on each class. It will only show coverage for only classes for which test classes are created.

    SELECT ApexTestClassId, TestMethodName, ApexClassorTriggerId, ApexClassOrTrigger.Name, NumLinesCovered, NumLinesUncovered FROM ApexCodeCoverage
    Apex Code Coverage

    ApexCodeCoverageAggregate : This object will represent aggregate code coverage test results for an Apex class or trigger. Code coverage will be shown per class for all classes.

    SELECT ApexClassOrTriggerId, ApexClassOrTrigger.Name, NumLinesCovered, NumLinesUncovered 
    FROM ApexCodeCoverageAggregate 
    WHERE ApexClassOrTriggerId != NULL AND ApexClassOrTrigger.Name != NULL AND NumLinesUncovered != NULL 
    AND (NumLinesCovered > 0 OR NumLinesUncovered > 0) AND NumLinesCovered != NULL 
    ORDER BY ApexClassOrTrigger.Name
    Apex Code Coverage

    ApexOrgWideCoverage : This object will represent total percentage of all classes in Salesforce org.

    SELECT PercentCovered FROM ApexOrgWideCoverage

    These SOQL will only fire when you select ‘Use Tooling API’ checkbox in Query Editor of developer console.

    Putting Code Coverage in Custom Object:

    Let us try to get all code coverage and put that in one of custom object to get code coverage list and status of classes. As above code is using Tooling API so let us create Apex class to get code coverage.

    Custom Object : Code Coverage (CodeCoverage__c)

    Object Fields:

    Field LabelField APIField Type
    ApexClass Or TriggerIdApexClassOrTriggerId__cText(255)
    ApexClass Or TriggerName
    ApexClassOrTriggerName__c

    Text(255)
    Apex Test ClassId
    ApexTestClassId__c

    Text(255)
    Code Coverage Name
    Name

    Auto Number
    Num Lines CoveredNumLinesCovered__c
    Number(5, 0)
    NumLinesUncovered
    NumLinesUncovered__c

    Number(5, 0)
    Test Method NameTestMethodName__cText(255)
    Code Coverage PercentageCodeCoveragePercentage__c
    Formula (Percent)
    Coverage StatusCoverageStatus__cFormula (Text)

    Formula fields detail:

    CodeCoveragePercentage__c: This formula will get code coverage percentage.

    NumLinesCovered__c/(NumLinesCovered__c+NumLinesUncovered__c)

    CoverageStatus__c : This will show colored flag based in percentage. For more then 75, show green color flag for other show red color flag.

    IMAGE(IF( CodeCoveragePercentage__c >0.75, "/img/samples/flag_green.gif", "/img/samples/flag_red.gif"),'Percantage')

    Let us see complete apex code to execute above mentioned SOQLs.

    Code Coverage Service : This class will create SOQLs for getting different type of code coverage using Tooling API. This class is using HTTPCallout ,a basic class, used to call any API.

    HttpCallout: A basic class to call any API. We will call tooling API using this class.

    Code Coverage Controller Class: This class will call CodeCoverageService class and change result based on our requirement. Right now this class is inserting record in object.

    call deleteRecords() when you want to delete existing record to insert new records.

    Above code will complete for code coverage retrieval. You can use below code to test it in developer console.

    CodeCoverageController.getAllCodeCoverage();

    If you want to execute above code from flow so that when you hit button, code coverage will refresh. For this use case, create a flow to execute a class. A new class with InvocableMethod is required so that flow can execute it.

    Call this apex class method from screen flow.

    Apex Code Coverage

    Use action element to call Refresh Code Coverage method. After that use screen element to show message that code coverage is completed.

    Test Page:

    Apex Code Coverage

    Check other Tooling API implementation:

    1. Field Access Explorer In lightning Web Component

    2. Extract list of all fields from Page Layout

    3. Find Referenced Metadata using Salesforce Dependency API

    4. Get All Used Custom Metadata Detail

    5. Call Tooling API from Lightning Web Component

    References:

    https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_code_coverage_intro.htm

    Related Posts

    Salesforce DevOps for Developers: Enhancing Code Quality and Deployment Efficiency

    Apex Code Coverage In Custom Object

    Get All Used Custom Metadata Detail

    Find Referenced Metadata using Salesforce Dependency API

    Extract list of all fields from Page Layout

    Field Access Explorer In lightning Web Component

    apex apex code coverage code coverage in Salesforce rest api salesforce tooling api
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleMonitor Salesforce API Limit
    Next Article Phone verification in Salesforce using VeriPhone API
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni6 Mins Read

    Unlock the Power of Vibe Coding in Salesforce

    April 30, 2025
    By Dhanik Lal Sahni5 Mins Read

    How to Implement Dynamic Queueable Chaining in Salesforce Apex

    April 21, 2025
    By Dhanik Lal Sahni5 Mins Read

    How to Implement Basic Queueable Chaining in Salesforce Apex

    March 31, 2025
    View 2 Comments

    2 Comments

    1. ukatta on November 21, 2022 2:43 pm

      Hi Dhanik,
      OrgWide code coverage and codeCoverageAggregate is giving wrong results like 55% or 60% code coverage where in which we have schedule class to run test classes daily and fetch report. We wonder if salesforce caching the results. once after deleting the codeCoverageAggregate records and run again giving correct results. Can you tell how can we overcome this wrong results issue.

      Reply
      • Dhanik Lal Sahni on November 29, 2022 7:56 pm

        Hello Uday,
        Ideally, it should delete records. Just check whether deleteRecords method is working properly or not.

        Thank You,
        Dhanik

        Reply
    Leave A Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (110) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) custom metadata types (5) design principle (9) file upload (3) flow (14) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (139) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce GraphQL API (3) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) shopify api (3) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (110) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) custom metadata types (5) design principle (9) file upload (3) flow (14) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (139) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce GraphQL API (3) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) shopify api (3) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.