unit-testingsalesforceapextest-class

Trying to Test Custom Lead Conversion Class but getting 0% Code Coverage


I am Testing below Class i.e. for Converting Lead and i am trying to write Test Class for this but this test class is not covering even 1% of Code.

global class LeadConversion
{
    Public Id leadId;
    public LeadConversion(ApexPages.StandardController stdController)
    {
        leadId = ApexPages.currentPage().getParameters().get('id');
    }
    public PageReference autoConvert()
    {
        Database.LeadConvert convertLead = new database.LeadConvert();
        convertLead.setLeadId(leadId);
        LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];
        convertLead.setConvertedStatus(convertStatus.MasterLabel);
        Database.LeadConvertResult convertLeadResult = Database.convertLead(convertLead);

        //TO get Account ID from Lead Conversion
        Id accountId = convertLeadResult.getAccountId();
        PageReference Page = new PageReference('https://----Here My Org URl---/'+accountId);
        Page.setRedirect(true);
        return Page;
    }
}

Test Class

@isTest
public class TestLeadConversion {
    static testMethod void LeadConvertedTest()
    {
        Lead lead1 = new Lead(LastName='Test',FirstName='Tester',Status='Known',Company='test');
        insert lead1;

        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(lead1.id);
        lc.setConvertedStatus('Closed - Converted');

        Database.LeadConvertResult lcr = Database.convertLead(lc);
        System.assert(lcr.isSuccess()); 
    }
}

Solution

  • Use below Code and See if that Works. And do remember to replace Your_Page_Name with your Page Name.

    @isTest
    public class TestLeadConversion {
        static testMethod void LeadConvertedTest()
        {
            //Create New Lead
            Lead lead1 = new Lead(LastName='Test',FirstName='Tester',Status='Known',Company='test');
            insert lead1;
    
            PageReference pageRef = Page.Your_Page_Name;
            //TO get Account ID from Lead Conversion
            pageRef.getParameters().put('id', lead1.id);
    
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController sc = new ApexPages.standardController(lead1);
            LeadConversion classController = new LeadConversion(sc);
            System.assertNotEquals(null, classController.autoConvert());
        }
    }