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

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: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 id="soContact" value="{!strContactId}" label="Contact Name" size="1">
                <apex:selectOptions value="{!lstContactInfo}" />



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();

if(strAccountId.length() > 1) { lc.setAccountId(strAccountId); }
if(strContactId.length() > 1) { lc.setContactId(strContactId); }

// 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];

// 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());
return prResult;  
} else {
return null;
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

private class TestXXCSRLeadConvertClass{

        static testMethod void TestXXCSRLeadConvertClass() {
           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';
   = 'test';
            l.street = 'test';
            l.state = 'CA';
   = 'United States';
            l.status = 'Qualified';
   = '';
   = '';
            insert l;
      Id leadId = l.Id;
  bolCreateOpp = false;
  //Create a reference to the VF page
  PageReference pageRef = Page.XXCSR_LEAD_CONVERT;

     //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 =;
       List<SelectOption> testacct = new List<SelectOption>();
       testacct = leadconvt.getlstCompanyInfo();
  List<SelectOption> testcon = new List<SelectOption>();
       testcon = leadconvt.getlstContactInfo();
             //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' ); 



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

All Answers

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).
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 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:-

public class TestAutoLeadConvert{
    static testMethod void convertLead(){
        Lead lead = new Lead();
        lead.Company='Trigger Test1';
        lead.LeadSource='GetTimely Online';
        insert lead;
        System.debug('Created and inserted lead');
         Database.LeadConvert lc = new database.LeadConvert();

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

     // Make sure conversion was successful


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

This was selected as the best answer
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 !
Yes. I did. Here are the attahcments. Regards, Pallavi Chennoju