0

Can any one help me out.The test code coverage value is showing less.In our org we have a trigger written and the test class,but the code coverage value is displaying only 41% .Any suggestion please.

Trigger :

public class CampaignMemberFunctions {
 public static void UpdateNewToEnterpriseDB(CampaignMember cm, Lead ld)
    {
if(ld.CreatedDate.addHours(6) > DateTime.Now()) 
 cm.New_to_EnterpriseDB__c = true;
    }
public static Boolean SyncStatus(CampaignMember cm, Lead ld, Contact ct, Map<String, CMStatusSettings__c> statusmap)
    {
     Boolean result = true;
     String newvalue;
     if(ct!= null)
        {
            if(statusmap.containsKey(cm.Response_Status__c))
            {
                newvalue = statusmap.get(cm.Response_Status__c).StatusMapping__c;
                if(newvalue == ct.Status__c)
                {
                    result = false;
                }
                else
                {
                    ct.Status__c = newvalue;
                }
            } else if(cm.Response_Status__c == 'Disqualified' || 
                        cm.Response_Status__c == 'Qualified - New Opportunity' ||
                        cm.Response_Status__c == 'Closed - Converted' )
            {
                newvalue = 'Closed - ' + ct.Account.Customer_Status__c + ' Account';
                if(ct.Status__c == newvalue)
                {
                    result = false;
                }
                else
                {
                    ct.Status__c = newvalue;
                }
                if(cm.Response_Status__c == 'Disqualified')
                {   // Set nuture time on disqualified status
                    Date newtimeout = Date.today().addDays((CMScoreEngine__c.getInstance('Default').NurtureTimeoutDays__c).intValue());
                    if(ct.Admin_Nurture_Timeout__c != newtimeout || ct.Lead_Score__c !=0 || ct.Campaign_Score__c !=0) result = true;
                    ct.Admin_Nurture_Timeout__c = newtimeout;
                    ct.Lead_Score__c = 0; 
                    ct.Campaign_Score__c = 0;   // Probably aren't using this one
                }
            } else
            {
                result = false;
            } 
 }

        else if(ld!=null)
        {
            if(statusmap.containsKey(cm.Response_Status__c))
            {
                newvalue = statusmap.get(cm.Response_Status__c).StatusMapping__c;
                if(newvalue==ld.Status)
                {
                    result = false;
                }
                else
                {
                    ld.Status = newvalue;
                }
            } else if(cm.Response_Status__c == 'Disqualified')
            {
                if(ld.Status=='Disqualified' && ld.Disqaulified_Reason__c == cm.Disqualified_Reason__c)
                {
                    result = false;
                }
                else
                {
                    ld.Status = 'Disqualified';
                    ld.Disqaulified_Reason__c = cm.Disqualified_Reason__c;
                    System.Debug('Disqualified reason being set to: ' + cm.Disqualified_Reason__c);
                }
            } else
            {
                result = false;
            }
 } 
        return(result);

    }

    // Search through the converted leads, opportunities and campaignmembers to sync if necessary
    public static void SyncAfterConversion(Map<Id,Lead> convertedleads, Map<Id, Opportunity>convertedops, Map<Id, CampaignMember> possiblecms) 
    {
        for(Lead ld: convertedleads.values())
        {
            // Grab the campaign member - this must be correct by original query
             CampaignMember cm = new CampaignMember();

             System.debug('@@@@@possiblecms.get(ld.admin_CMSourceId__c)'+possiblecms.get(ld.admin_CMSourceId__c));
             cm = possiblecms.get(ld.admin_CMSourceId__c);
             System.debug('@@@@@cm '+cm );
           if(cm!=null)
           {  
            // We know this lead is converted. Let's get the opportunity.             
            if(ld.ConvertedOpportunityId != null)
            {
                Opportunity opp = convertedops.get(ld.ConvertedOpportunityId);
                opp.PMM_stage__c = cm.PMM_Stage__c;
                opp.Product_Interest__c = cm.Product_Interest__c;
                opp.Buyer__c = cm.Buyer__c;
                opp.New_to_EnterpriseDB__c = cm.New_to_EnterpriseDB__c;
                opp.Problem_to_Solve__c = cm.Problem_to_Solve__c;
                opp.Any_OSS_in_current_stack__c = cm.Any_OSS_in_current_stack__c;
                opp.Total_of_Databases_in_your_Org__c = cm.Total_of_Databases_in_your_Org__c;
                opp.Primary_Database__c = cm.Primary_Database__c;
                opp.of_Postgres_Database_Servers__c = cm.of_Postgres_Database_Servers__c;
                opp.Just_learning_about_EnterpriseDB__c = cm.Just_learning_about_EnterpriseDB__c;
                opp.Project_Requires_a_Net_New_DB__c = cm.Project_Requires_a_Net_New_DB__c;
                opp.Timeframe_To_Production__c = cm.Timeframe_To_Production__c;
                opp.Budget__c = cm.Budget__c;
                opp.User__c = cm.User__c;
                opp.Champion__c = cm.Champion__c;
                opp.Decision_Maker__c = cm.Decision_Maker__c;
                cm.Response_Status__c = 'Qualified - New Opportunity';
                cm.Opportunity_Name__c = opp.Id;
                cm.Opportunity_Create_Date__c = Date.Today();
            }

            else
            {                          
                if(cm.lead.status!=null)
                 {
                    cm.Response_Status__c = cm.lead.status;
                 }
            }
            cm.admin_IsConverted__c = true; 
          }           
        }   

    }

    public static void EmailErrorMessage(String message)
    {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {'edbnotify@bearcavern.com', 'roanbear@gmail.com'});
        mail.setSenderDisplayName('APEX notifier');
        mail.setSubject('SFDC/Eloqua Data Creation Error');
        mail.setPlainTextBody(message);
        List<Messaging.SendEmailResult> results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        for(Messaging.SendEmailResult r: results)
        {
            System.debug('Result of Email sent ' + r.isSuccess());
            if(!r.isSuccess())
            {
                for(Messaging.SendEmailError sme: r.getErrors())
                {
                    for(String s: sme.getFields())  System.Debug('Error for field ' + s );      
                    System.Debug('Error message ' + sme.getMessage());
                    System.Debug('StatusCode ' + sme.getStatusCode());
                }}}}}

Test Class:

@isTest(seealldata=true)
Public class TestCampaignMemberFunctions {

    Public static testMethod void TestCreationDate() {

        Lead ld2 = [select ID, CreatedDate, IsConverted from LEAD where CreatedDate < :DateTime.Now().addHours(-7) and IsConverted=False  LIMIT 1];
        Campaign cam = new Campaign(Name='campname');      
        insert cam;       
        Account a = new Account();
        a.Name ='My Company';
        Insert a;                   

        Lead ld = new Lead();
        ld.Company='colead1';  
        ld.LastName ='colead1_'+String.valueOf(System.now());
        ld.status= 'Junk';        
        ld.admin_CMSourceId__c= cam.Id;              
        insert ld;

        Contact con = new Contact(LastName ='Test');        
        Insert con;               
        Test.StartTest();
        CampaignMember mc1 = new CampaignMember(CampaignId = cam.Id,Product_Interest__c='Services',Response_Status__c='Disqualified',status= 'Junk', LeadId=ld.Id);
        CampaignMember mc2 = new CampaignMember(CampaignId = cam.Id, LeadId=ld2.Id);
        insert mc1;
        insert mc2; 
        Opportunity opp =new Opportunity();
        opp.Product_Interest__c=mc1.Product_Interest__c;

        opp.PMM_stage__c = mc1.PMM_Stage__c;
        opp.Buyer__c = mc1.Buyer__c;
        opp.New_to_EnterpriseDB__c =mc1.New_to_EnterpriseDB__c;
        opp.Problem_to_Solve__c = mc1.Problem_to_Solve__c;
        opp.Any_OSS_in_current_stack__c = mc1.Any_OSS_in_current_stack__c;
        opp.Total_of_Databases_in_your_Org__c = mc1.Total_of_Databases_in_your_Org__c;
        opp.Primary_Database__c =mc1.Primary_Database__c;
        opp.of_Postgres_Database_Servers__c = mc1.of_Postgres_Database_Servers__c;
        opp.Just_learning_about_EnterpriseDB__c = mc1.Just_learning_about_EnterpriseDB__c;
        opp.Project_Requires_a_Net_New_DB__c = mc1.Project_Requires_a_Net_New_DB__c;
        opp.Timeframe_To_Production__c = mc1.Timeframe_To_Production__c;
        opp.Budget__c = mc1.Budget__c;
        opp.User__c = mc1.User__c;
        opp.Champion__c = mc1.Champion__c;
        opp.Decision_Maker__c =mc1.Decision_Maker__c;

        opp.Name='Testing';
        opp.StageName='Closed Lost';
        opp.CloseDate=System.today(); 
        Insert opp;       
        CampaignMember mc1res = [Select Id, New_to_EnterpriseDB__c,Response_Status__c from CampaignMember where Id = :mc1.id ];
        CampaignMember mc2res = [Select Id, New_to_EnterpriseDB__c from CampaignMember where Id = :mc2.id ];        
        System.assert(mc1res.New_to_EnterpriseDB__c);
        System.assert(! mc2res.New_to_EnterpriseDB__c);
        Map<String, CMStatusSettings__c> statusmap = new Map<String, CMStatusSettings__c>();

        Map<Id,Lead> convertedleads = new Map<Id,Lead>();                   
        convertedleads.put(ld.Id,ld);

        Map<Id, Opportunity> convertedops= new Map<Id, Opportunity>();        
        convertedops.put(opp.Id,opp);

        Map<Id, CampaignMember> possiblecms= new Map<Id, CampaignMember>();        
        possiblecms.put(mc1.Id,mc1);                                 
        CampaignMemberFunctions  cmf = new CampaignMemberFunctions();
        CampaignMemberFunctions.SyncStatus( mc1res,ld,con,statusmap);
        System.debug('@@@@@convertedleads'+convertedleads);
        System.debug('@@@@@possiblecms'+possiblecms);
        System.debug('@@@@@convertedops'+convertedops);

        CampaignMemberFunctions.SyncAfterConversion(convertedleads,convertedops,possiblecms);
        CampaignMemberFunctions.EmailErrorMessage('testmessage');     
        Test.StopTest();    
        }              
}

The lines which are not getting covered in Developer Console are :

{
                newvalue = statusmap.get(cm.Response_Status__c).StatusMapping__c;
                if(newvalue == ct.Status__c)
                {
                    result = false;
                }
                else
                {
                    ct.Status__c = newvalue;
                }
            } else if(cm.Response_Status__c == 'Disqualified' || 
                        cm.Response_Status__c == 'Qualified - New Opportunity' ||
                        cm.Response_Status__c == 'Closed - Converted' )
            {
{
                result = false;
            }  }
else if(ld!=null)
        {
            if(statusmap.containsKey(cm.Response_Status__c))
            {
                newvalue = statusmap.get(cm.Response_Status__c).StatusMapping__c;
                if(newvalue==ld.Status)
                {
                    result = false;
                }
                else
                {
                    ld.Status = newvalue;
                }
            } else if(cm.Response_Status__c == 'Disqualified')
            {
                if(ld.Status=='Disqualified' && ld.Disqaulified_Reason__c == cm.Disqualified_Reason__c)
                {
                    result = false;
                }
                else
                {
                    ld.Status = 'Disqualified';
                    ld.Disqaulified_Reason__c = cm.Disqualified_Reason__c;
                    System.Debug('Disqualified reason being set to: ' + cm.Disqualified_Reason__c);
                }
            } else
            {
                result = false;
            }
if(ld.ConvertedOpportunityId != null)
            {
                Opportunity opp = convertedops.get(ld.ConvertedOpportunityId);
                opp.PMM_stage__c = cm.PMM_Stage__c;
                opp.Product_Interest__c = cm.Product_Interest__c;
                opp.Buyer__c = cm.Buyer__c;
                opp.New_to_EnterpriseDB__c = cm.New_to_EnterpriseDB__c;
                opp.Problem_to_Solve__c = cm.Problem_to_Solve__c;
                opp.Any_OSS_in_current_stack__c = cm.Any_OSS_in_current_stack__c;
                opp.Total_of_Databases_in_your_Org__c = cm.Total_of_Databases_in_your_Org__c;
                opp.Primary_Database__c = cm.Primary_Database__c;
                opp.of_Postgres_Database_Servers__c = cm.of_Postgres_Database_Servers__c;
                opp.Just_learning_about_EnterpriseDB__c = cm.Just_learning_about_EnterpriseDB__c;
                opp.Project_Requires_a_Net_New_DB__c = cm.Project_Requires_a_Net_New_DB__c;
                opp.Timeframe_To_Production__c = cm.Timeframe_To_Production__c;
                opp.Budget__c = cm.Budget__c;
                opp.User__c = cm.User__c;
                opp.Champion__c = cm.Champion__c;
                opp.Decision_Maker__c = cm.Decision_Maker__c;
                cm.Response_Status__c = 'Qualified - New Opportunity';
                cm.Opportunity_Name__c = opp.Id;
                cm.Opportunity_Create_Date__c = Date.Today();
            }

            else
            {                          
                if(cm.lead.status!=null)
                 {
                    cm.Response_Status__c = cm.lead.status;
                 }
            }
            cm.admin_IsConverted__c = true; 
          } 

I shall aprreciate your help.

  • It will be much more easier to help if you add more details as to which lines in the class are covered and which are not and what have to tried to cover the uncovered lines. – Sam Mar 21 '16 at 6:44
  • @Mugambo:Thanks for your response.I have added the uncovered lines in the post stating as The lines which are not getting covered in Developer Console .In test class i added the opportunity fields as per the trigger in the class but those are not getting covered.Any suggestions very much appreciated. – SalesforceCRM AccountCRM Mar 21 '16 at 6:54
  • you are using many if statements. Make sure that your test class executes as many if statements as possible. The more you cover the higher your coverage will be. – Andree Wille Mar 21 '16 at 10:24
  • @Andree Wille:Thanks for the reply.I have added three testmethods based on the if condition,but the opportunity fields are not getting covered.Any suggestion please. – SalesforceCRM AccountCRM Mar 21 '16 at 10:31
  • @SalesforceCRMAccountCRM if i understand your code correctly then you need to set ConvertedOpportunityId on at least no Lead to something diffent than Null because then the if clause if(ld.ConvertedOpportunityId != null) is true and executes the code containing the opportunity fields. – Andree Wille Mar 21 '16 at 10:38
2

REASON for low coverage:-

The map "statusmap" is blank while its being passed in a method called "SyncStatus" in test class. So below IF condition is not met which caused low coverage.

if(statusmap.containsKey(cm.Response_Status__c)){
}

SOLUTION:-

In your test Class, Please create the data in customSetting "CMStatusSettings__c" and put the values in a Map called "statusmap".

Please Use the below code in your test class before calling "SyncStatus" method:

*// 1) Create custom setting data here*:

CMStatusSettings__c custSetting = new CMStatusSettings__c();

custSetting.Name= 'Test';

*//Add all required fields* :

Insert custSetting;

*// 2) Put values in a Map*:

statusmap.put(mc1res.Response_Status__c, custSetting);

*//Then call this method*:

CampaignMemberFunctions.SyncStatus(mc1res,ld,con,statusmap);

Please mark this as a solution if it works for you.

  • :Thanks for the response.As suggested i tried adding the CMStatusSettings__c and inserted ,but when i put values in map i.e.statusmap.put(mc1res.Response_Status__c, custSetting); the code coverage is getting reduce (showing as 33%),if i comment the line then the code coverage is displaying as 44%.I have different three methods with the if conditions for the Response_Status__c ,but the opportunity fields are not getting covered.Any Suggestions very much appreciated. – SalesforceCRM AccountCRM Mar 21 '16 at 10:43
  • Please create a new test method with the existing code and add my code in a new test method. – iamsfdc Mar 21 '16 at 11:29
  • :As Suggested i have added another test method and included the statusmap ,now the code coverage is displaying as 48% but the opportunity fields are not getting covered even if i give the values for the fields.Any help very much appreciated. – SalesforceCRM AccountCRM Mar 21 '16 at 11:47
  • Please convert the Lead in one of the test methods in Test Class using below code : Map<Id,Lead> convertedleads = new Map<Id,Lead>(); // START Convert the Lead into Test Class Database.LeadConvert lc = new Database.LeadConvert(); lc.setLeadId(ld.Id); lc.setOpportunityName('Testing'); LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1]; lc.setConvertedStatus(convertStatus.MasterLabel); Database.LeadConvertResult lcr = Database.convertLead(lc); System.assert(lcr.isSuccess()); convertedleads.put(ld.Id,ld); – iamsfdc Mar 21 '16 at 12:16
  • :The system throws an error as:System.DmlException: ConvertLead failed. First exception on row 0; first error: INVALID_STATUS, invalid convertedStatus: Qualified - Legacy: [Status] – SalesforceCRM AccountCRM Mar 21 '16 at 13:28

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