0

I have a trigger on lead and wrote a unittest but are not getting any codecoverage. What amI missing.

Trigger

trigger LeadTrigger on Lead (before insert, before update, before delete, after insert, after update, after delete, after undelete) {

    LeadTriggerHandler handler = new LeadTriggerHandler();

    //Before Insert
    if(Trigger.isInsert && Trigger.isBefore){
        handler.OnBeforeInsert(Trigger.new);
    }
    //After Insert
    else if(Trigger.isInsert && Trigger.isAfter){
        handler.OnAfterInsert(Trigger.new);
    }
    //Before Update
    else if(Trigger.isUpdate && Trigger.isBefore){
        handler.OnBeforeUpdate(Trigger.old, Trigger.new, Trigger.newMap);
    }
    //After Update
    else if(Trigger.isUpdate && Trigger.isAfter){
        handler.OnAfterUpdate(Trigger.old, Trigger.new, Trigger.newMap);
    }
}

Unittest

@isTest
public class LeadTriggerTest{
    // Create Lead
    static testMethod void convertLead(){
        Lead lead = new Lead();
        lead.FirstName ='FirstName';
        lead.LastName = 'LastName';
        lead.Company = 'Company';
        lead.isActive__c = true;
        lead.Email = 'Test1234A@test.nl';
        lead.Phone = '0612345678';
        lead.LeadSource='LeadSource';
        lead.name__c= 'A New House';
        insert lead;

        String Files = 'files';

        ContentVersion conVer = new ContentVersion();
        conVer.ContentLocation = 'S'; // S specify this document is in SF, use E for external files
        conVer.PathOnClient = 'ionicLogo.png'; // extension is very important for preview.
        conVer.Title = 'Property'; // Display name of the files
        conVer.VersionData = EncodingUtil.base64Decode(Files); // converting binary string to Blog
        insert conVer;       
        // First get the content document Id from ContentVersion
        Id conDoc = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:conVer.Id].ContentDocumentId;

        //Create ContentDocumentLink
        ContentDocumentLink cDe = new ContentDocumentLink();
        cDe.ContentDocumentId = conDoc;
        cDe.LinkedEntityId = lead.Id; // you can use objectId,GroupId etc
        cDe.ShareType = 'I'; // Inferred permission
        cDe.Visibility = 'AllUsers';
        insert cDe;

        System.debug('Created and inserted lead');
        test.startTest();
        lead.status = 'converted';
        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(lead.Id);

        LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        Database.LeadConvertResult lcr = Database.convertLead(lc);

        //Make sure conversion was successful
        System.assert(lcr.isSuccess());
        test.stopTest();
    } 
}

Handler

public with sharing class LeadTriggerHandler {

    private boolean isExecuting = false;
         public void OnAfterUpdate(List<Lead> oldLeads, List<Lead> updatedLeads, Map<Id, Lead> LeadMap){
            //AFTER UPDATE LOGIC
             Set<Id> Ids = new Set<Id>();
        for (Lead l : updatedLeads){
            if(l.status=='converted'){
                Ids.add(l.Id);
            }
        }
        List<ContentDocumentLink> ContDocLinksLead = [
            SELECT ContentDocumentId, LinkedEntityId  
            FROM ContentDocumentLink 
            WHERE LinkedEntityId IN: Ids
        ];
      //system.debug('ContDocLinksLead[0].LinkedEntityId '+ ContDocLinksLead[0].LinkedEntityId);

        if(Ids.size()!=null && ContDocLinksLead.size()!=null){
            List<property__c> propList = new List<property__c>();
            for(id lId: Ids){
           property__c prop = new property__c(name = 'test',leadid__c = lId );
                propList.add(prop);
                }
                insert propList; 
            system.debug('propList: '+propList);

         map<id,property__c> MapIdProp = new map<id,property__c>();
        for(integer x=0;x<propList.size();x++){
            MapIdProp.put(propList[x].leadid__c,propList[x]);
        }
         system.debug('MapIdProp: '+MapIdProp);
            system.debug('MapIdProp.get(Link.LinkedEntityId).id: '+MapIdProp.keyset());        
        if(ContDocLinksLead.size()!=null){
            List<ContentDocumentLink> LinkList = new List<ContentDocumentLink>();
            for(ContentDocumentLink Link: ContDocLinksLead){
                ContentDocumentLink newLink = new ContentDocumentLink();
                newLink.ContentDocumentId = Link.ContentDocumentId;
                system.debug('Link.LinkedEntityId: '+Link.LinkedEntityId);
                newLink.LinkedEntityId = MapIdProp.get(Link.LinkedEntityId).id;
                newLink.ShareType = 'I';
                newLink.Visibility = 'AllUsers';
                LinkList.add(newLink);
            }
            Insert LinkList;
        }
               }
        }
  • 1
    Your trigger has all logic in handler class which is not included in the post. Would be nice if you could narrow down your problem and share where exactly are you stuck with the test class coverage. – Raul Jun 7 '19 at 11:39
  • @raul I didn placed the handler to advoid to much cluttering.I added it now. I issue is that I get a succes on my test but completely not coverage. – Thomas Jun 7 '19 at 11:57
  • 1
    Which specific lines are you unable to cover? We can't help without some specifics from you. – David Reed Jun 7 '19 at 11:58
  • @DavidReed Thats my issue I have zero coverage so no specific lines. My test says succes but I have zero coverage. – Thomas Jun 7 '19 at 12:00
  • 1
    This does not make sense, could you the test class again from dev console (or apex test execution) after clearing the test data, here is an article: Eliminate bad code coverage data for Apex classes – Raul Jun 7 '19 at 12:15
2

At times, things go wrong with test coverage calculation of test classes resulting in this behavior.

Salesforce help now has a nice knowledge article: Eliminate bad code coverage data for Apex classes, quoting the information for reference:

Issue: There may be times where we see a different code coverage value than the actual value. This might be caused due to bad code coverage data or aggregate results from previous test runs.

Solution: To eliminate any bad code coverage data in your organization you can follow the steps mentioned below.


For Classic (First re-run all tests in your organization followed by below steps):

  1. Navigate to Setup > Develop > Apex Test Execution, Click on View Test History and on Apex Test Results page, click on Clear test data.

  2. Navigate to Setup > Develop > Apex Classes, click on Compile all classes

  3. Navigate to Setup > Develop > Apex Test Execution, click on Select tests, from test classes popup select "My Namespace", Select all classes and Click run

  4. Navigate to Setup > Develop > Apex Classes, and click on Estimate your organization's code coverage


For Lightning experience (First re-run all tests in your organization followed by below steps):

  1. Navigate to Setup > Custom Code > Apex Test Execution, Click on View Test History and on Apex Test Results page, click on Clear test data.

  2. Navigate to Setup > Custom Code > Apex Classes, click on Compile all classes

  3. Navigate to Setup > Custom Code > Apex Test Execution, click on Select tests, from test classes popup select "My Namespace", Select all classes and Click run

  4. Navigate to Setup > Custom Code > Apex Classes, and click on Estimate your organization's code coverage


To Remove Bad data:

  1. Open Developer console and Execute the following query in "Query Editor" with "Tooling API" checked.

    SELECT Id, NumLinesUncovered FROM ApexCodeCoverageAggregate 
        WHERE NumLinesUncovered = NULL 
    
  2. Select all the returned rows and hit "Delete Row"

  3. Try to estimate the code coverage again
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.