function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Pallavic14Pallavic14 

Help with test class for lead conversion

Here is my VF page for lead conversion. not able to figure out what else needs in my test class to increase the coverage. PLease help.

<apex:page standardController="Lead" extensions="XXCSRLeadConvertClass"   title="Convert Lead" id="pgConvertLead">

<apex:form id="frmConvert">

    <apex:actionFunction name="afOpportunity" action="{!doNothing}" rerender="pbsConvert" immediate="true" />

    <apex:pageBlock title="Convert Lead" mode="edit">
   
        <apex:pageBlockButtons >
            <apex:commandButton id="cmdConvert" action="{!convertLead}" value="Convert" />
            <apex:commandButton id="cmdCancel" action="{!cancel}" value="Cancel" />
        </apex:pageBlockButtons>
       
        <apex:messages ></apex:messages>
       
        <apex:pageBlockSection id="pbsConvert" title="Convert Lead" columns="1">
                       
            <apex:inputField id="ifOwnerId" value="{!ldSource.OwnerId}" />
            <apex:selectList id="soAccount" value="{!strAccountId}" label="Account Name" size="1">
                <apex:selectOptions value="{!lstCompanyInfo}" />
            </apex:selectList>
            <apex:selectList id="soContact" value="{!strContactId}" label="Contact Name" size="1">
                <apex:selectOptions value="{!lstContactInfo}" />
            </apex:selectList>
                      
        </apex:pageBlockSection>
   
    </apex:pageBlock>

</apex:form>

</apex:page>

Here is extension class

public class XXCSRLeadConvertClass {
public Lead ldSource {get;set;}
public Boolean bolCreateOpp {get;set;}
public String strAccountId {get;set;}
public String strContactId {get;set;}



//////////////////////////
// Constructors / GETers
//////////////////////////
public XXCSRLeadConvertClass(ApexPages.StandardController scMain) {



ldSource = [SELECT Id, FirstName, LastName, OwnerId, Company, Street, City, State, PostalCOde, Country, Phone, Fax,Status,ApprovalStatus__c FROM Lead WHERE Id = :scMain.getId()];
bolCreateOpp = false;

    
}

public List<SelectOption> getlstCompanyInfo() {

String strCompanyWildcard = '%' + ldSource.Company + '%';
List<Account> lstAcct = [SELECT Id, Name, Owner.Name FROM Account WHERE Name LIKE :strCompanyWildcard];

List<SelectOption> lstCompanies = new List<SelectOption>();

// Add New Account if not found
lstCompanies.add(new SelectOption('1','Create New Account: ' + ldSource.Company));

// Add found Accounts to SelectList
for(Account a : lstAcct) {
lstCompanies.add(new SelectOption(a.Id, 'Attach to Existing: ' + a.Name + ' (' + a.Owner.Name + ')'));
}

return lstCompanies;      
}

    public List<SelectOption> getlstContactInfo(){
       
       string strContactFirst = '%'+ldSource.FirstName+'%';
        string strContactLast = '%'+ldSource.LastName+'%';
        List<Contact> lsContact = [select Id ,FirstName,LastName,AccountId,Owner.Name from Contact where (FirstName like : strContactFirst and LastName like :strContactLast)
                                   and AccountId = :[select Id from Account where Name like :ldSource.Company]];
       List<SelectOption> lstContact = new List<SelectOption>();
       
        // Add New Contact if not found
lstContact.add(new SelectOption('1','Create New Contact: ' + ldSource.FirstName+''+ldSource.LastName));

// Add found Accounts to SelectList
for(Contact c : lsContact) {
lstContact.add(new SelectOption(c.Id, 'Attach to Existing: ' + c.FirstName +' '+c.LastName+ ' (' + c.Owner.Name + ')'));
    }
return lstContact;         
    }
//////////////////////////
// Action Methods
//////////////////////////

public void doNothing() {  }

public PageReference convertLead() {

//check if status = qualified and Approved
if (ldSource.Status == 'Qualified' && ldSource.ApprovalStatus__c == 'Approved'){


// Create LeadConvert object
Database.LeadConvert lc = new Database.LeadConvert();

        
lc.setLeadId(ldSource.Id);
lc.setOwnerId(ldSource.OwnerId);
if(strAccountId.length() > 1) { lc.setAccountId(strAccountId); }
if(strContactId.length() > 1) { lc.setContactId(strContactId); }
lc.setDoNotCreateOpportunity(bolCreateOpp);

// Set Opportunity Name
if(bolCreateOpp == true) { lc.setOpportunityName(ldSource.Company); }

// Set Lead Converted Status
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
lc.setConvertedStatus(convertStatus.MasterLabel);



// Convert!
Database.LeadConvertResult lcr = Database.convertLead(lc);

// Mop up Opportunity
if(bolCreateOpp == true) {
Opportunity o = new Opportunity(Id=lcr.getOpportunityId());
update o;
}
// Redirect...
PageReference prResult;
if(lcr.isSuccess()) {
prResult = new PageReference('/' + lcr.getAccountId());
prResult.setRedirect(true);
return prResult;  
} else {
return null;
}
}else{
ldSource.addError('Lead cannot be converted without Lead status Qualified and Approved !'); 
      ldSource.addError('Please Go back to Lead screen to change status'); 
    }
   
return null;}
}


Here is my test code

@IsTest(seealldata=true)
private class TestXXCSRLeadConvertClass{

        static testMethod void TestXXCSRLeadConvertClass() {
      
       test.startTest();
           Boolean bolCreateOpp;
           String strAccountId;
     String strContactId;
            Lead l = new Lead();
            l.FirstName = 'CRM Testing First';
            l.LastName = 'CRM Testing Last';
            l.Company = 'CRM Testing INCtest';
            l.description = 'Test descr';
            l.city = 'test';
            l.street = 'test';
            l.state = 'CA';
            l.country = 'United States';
            l.status = 'Qualified';
            l.email = 'test@testnetgear.com';
            l.website = 'www.testcrm.com';
            l.ApprovalStatus__c='Approved';
            l.RecordTypeId='012110000004b9Q';
             
        
            insert l;
       
      Id leadId = l.Id;
  bolCreateOpp = false;
  //Create a reference to the VF page
  PageReference pageRef = Page.XXCSR_LEAD_CONVERT;
        Test.setCurrentPageReference(pageRef);

     //Create an instance of the controller extension and call the autoRun method.
  //autoRun must be called explicitly even though it is "autoRun".
  ApexPages.StandardController sc = new ApexPages.standardController(l);
  XXCSRLeadConvertClass leadconvt = new XXCSRLeadConvertClass(sc);
   String nextPage = sc.save().getUrl();
 
      
       List<SelectOption> testacct = new List<SelectOption>();
       testacct = leadconvt.getlstCompanyInfo();
        system.debug(testacct);
    
       
  List<SelectOption> testcon = new List<SelectOption>();
       testcon = leadconvt.getlstContactInfo();
        system.debug(testcon);
 
   leadconvt.doNothing();
 
             //Retrieve the converted Lead info and the opps and roles.
   l = [select Id, IsConverted, ConvertedAccountId, ConvertedContactId ,Status, ApprovalStatus__c,
    Company,OwnerId,firstname,lastname,city,country from Lead where Id = :leadId];
         
          system.assert(!l.IsConverted,'Lead Converted' ); 
          test.stopTest();
        


        }
  
        

}

Thanks
Pallavi
Best Answer chosen by Pallavic14
Gigi.OchoaGigi.Ochoa
Before you call convertLead() method, set the contactId and accountId.
leadconvt.strAccountId= '1';
leadconvt.strContactId= '1';
leadconvt.convertlead();

All Answers

Gigi.OchoaGigi.Ochoa
You need to call convertLead() method in your test class.

If you go in the develop console, run you tests and open your class, you should see exactly which lines are not covered.

Also as an FYI, it is best practice not to use seealldata=true, but rather create your own test data (for your accounts and contacts).
Pallavic14Pallavic14
When i add that call i get nullpointer exception.
I can see what lines in eclipse. I have no experience in apex. jsut doing by looking at examples.as i get very few customization requirements.
Vandana RattanVandana Rattan
Hi Pallavi,

I wrote a trigger for Lead Conversion some time back along with the test class. You need to call the convertLead() as shown in the test class below:-

@isTest
public class TestAutoLeadConvert{
    static testMethod void convertLead(){
        test.startTest();
        Lead lead = new Lead();
        lead.FirstName='Trigger1';
        lead.LastName='Test1';
        lead.Company='Trigger Test1';
        lead.LeadSource='GetTimely Online';
        lead.Handicap__c=12;
        lead.PostCode__c='1234';
        insert lead;
        
        System.debug('Created and inserted lead');
        
         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();
        
        
            
    } 
}

You need to explicitly call convertLead and use assertions to check for success or failure. Hope this helps.
Gigi.OchoaGigi.Ochoa
Before you call convertLead() method, set the contactId and accountId.
leadconvt.strAccountId= '1';
leadconvt.strContactId= '1';
leadconvt.convertlead();

This was selected as the best answer
Pallavic14Pallavic14
Thank you very much Gigi. That worked.
Laurent JantzenLaurent Jantzen
Hi Pallavic14, did you find a solution for your test class ? I'm working on a similar code and can't cover more than 26%...
Hope you can help me !
Pallavic14Pallavic14
Yes. I did. Here are the attahcments. Regards, Pallavi Chennoju