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
Shruthi NarsiShruthi Narsi 

Adding exception in test class

I have wirtten the below test class. The code coverage is only 92% I want to make it to 100%

Apex class

public class ConvertTheLead
{
    public Lead__c leadObj{get;set;}
    List<Account> acctList = new List<account>();
    public static final string stage='prospecting';
    public static final string status='Qualified';
    
    public ConvertTheLead(ApexPages.StandardController stdController)
    {
        leadObj = new Lead__c();
        Lead__c ldId =  (Lead__c)stdController.getRecord();
        leadObj = [select id,Company__c,State_Province__c,Phone__c,Street__c,Name__c,MobilePhone__c,Email__c,LeadSource__c,Industry__c,No_of_Employees__c,Annual_Revenue__c,Status__c,Name1__c     from lead__c where id =:ldId.Id];
    }
    
    public PageReference RedirecttoSite()
    {
        String currentLead = '/' + leadObj.Id;
        PageReference pageRef = new PageReference(currentLead);
        return pageRef;
    }
    
    public PageReference convertbutton()
    {
        
        if(leadObj.Status__c != status){
            ApexPages.Message errormsg1 = new ApexPages.Message(ApexPages.severity.ERROR,'Please change the lead status to qualified & then try to convert the lead');
            ApexPages.addMessage(errormsg1);
            return null;
        }
        try{
            Account acc = new Account();
            acc.Name = leadObj.Company__c;
            acc.BillingState= leadObj.State_Province__c;
            acc.Phone = leadObj.Phone__c;
            acc.Industry = leadObj.Industry__c;
            acc.AnnualRevenue = leadobj.Annual_Revenue__c;
            acc.NumberOfEmployees = integer.valueof(leadobj.No_of_Employees__c);
            insert acc;
            
            Opportunities__c opp = new Opportunities__c();
            opp.Name = leadObj.Name1__c    ;
            opp.Account_Name__c = acc.Id;
            opp.Close_Date__c= system.today()+30;
            opp.Stage__c = stage;
            opp.Lead_Source__c = leadobj.LeadSource__c;
            insert opp;
            
            Contact cc = new Contact();
            cc.LastName = leadObj.Name1__c;
            cc.Email = leadObj.Email__c;
            cc.Phone = leadObj.Phone__c;
            cc.AccountId = acc.Id;
            cc.Opportunities__c = opp.Id;
            cc.Phone = leadObj.Phone__c;
            cc.MobilePhone = leadobj.MobilePhone__c;
            cc.Address__c = leadobj.Street__c;
            insert cc;
            
            if(acc.Id!=null){
                list<Lead__c> Listleads = [select id from Lead__c where id=:leadObj.Id];
                if(!Listleads.isEmpty()){
                    Delete Listleads;
                }
                String currentAccount = '/' + acc.Id;
                PageReference pageRef = new PageReference(currentAccount);
                pageRef.setRedirect(true);
                return pageRef;
            }
        }catch(Exception e){
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.confirm,e.getMessage());
            ApexPages.addMessage(errormsg);
        }
        
        return null;
    }
}

Vf page

<apex:page standardController="Lead__c" cache="true" extensions="ConvertTheLead" action="{!convertbutton}" lightningStylesheets="true" docType="html-5.0">
    <head>
        <apex:slds /> 
    </head> 
    <apex:form > 
        <apex:pageMessages ></apex:pageMessages>
        <div class="slds-page-header">
            <div class="slds-page-header__row">
                <div class="slds-page-header__col-title">
                    <div class="slds-media">
                        <div class="slds-media__figure">
                            <span class="slds-icon_container slds-icon-standard-lead" title="Lead Convert"> 
                                <apex:commandLink action="{!RedirecttoSite}">
                                    <img src="/apexpages/slds/latest/assets/icons/action/lead_convert_60.png"/> 
                                </apex:commandLink>
                                <span class="slds-assistive-text">Lead</span>
                            </span>
                        </div>
                        <div class="slds-media__body">
                            <div class="slds-page-header__name">
                                <div class="slds-page-header__name-title">
                                    <h1>
                                        <span class="slds-page-header__title slds-truncate" title="{!leadObj.Name1__c}">{!leadObj.Name1__c}</span>
                                    </h1>
                                </div>
                            </div>
                            <p class="slds-page-header__name-meta">Lead Convert&nbsp;&nbsp;<apex:commandLink value="Redirect to Lead" style="font-weight:bold;font-size:15px;" action="{!RedirecttoSite}"/></p> 
                        </div> 
                    </div>
                </div>
            </div>
        </div> 
    </apex:form> 
</apex:page>

test class

@isTest
public class ConvertTestClass {
     
    public static testMethod void test1() {
        
        Lead__c ld = new Lead__c ();
        ld.First_Name__c = 'Test';
        ld.Name    ='first';
        ld.Company__c ='Test company';
        ld.Status__c = 'Qualified';
        insert ld;
        
        Test.StartTest(); 

        PageReference pageRef = Page.RedirectingToLead; 
        Test.setCurrentPage(pageRef);


        ApexPages.StandardController sc = new ApexPages.StandardController(ld);
        ConvertTheLead testAccPlan = new ConvertTheLead(sc);
        testAccPlan.RedirecttoSite();
        testAccPlan.convertbutton();
        Test.StopTest();
        
    }
    
    public static testMethod void test2() {
        
        Lead__c ld = new Lead__c ();
        ld.First_Name__c = 'Test';
        ld.Name    ='first';
        ld.Company__c ='Test company';
        // Set Status as any valid value other then "Qualified"
        ld.Status__c = 'New'; 
        insert ld;
        
        Test.StartTest(); 

        PageReference pageRef = Page.RedirectingToLead; 
        Test.setCurrentPage(pageRef);


        ApexPages.StandardController sc = new ApexPages.StandardController(ld);
        ConvertTheLead testAccPlan = new ConvertTheLead(sc);
        testAccPlan.RedirecttoSite();
        testAccPlan.convertbutton();
        Test.StopTest();
        
    }
    
}

User-added image
Danish HodaDanish Hoda
Hi Shruthi,
Try sending blank value in ApexPages.StandardController sc = new ApexPages.StandardController()
Andrew GAndrew G
First, why are we worried about 100% coverage, if we don't have asserts?

Second, if we check where uncovered code is, it is part of a Try / Catch structure - to get the Catch to fire you will need to force an error in the Try structure.  Since this is all about inserting records, that would be tricky.  Since there is a delete call in the TRY structure, create 2 x user profiles, one with delete access, one without, then use the Runas (User) feature of the test class to see if that would cause the CATCH structure to become involved.

Now an aside, we have 2 x test methods, identical in how they invoke all the methods of the class,with the exception of the Status of the Lead.  Why is that?   If the second test method (where the Status is "New" ) has the purpose of trying to cover the code segment:
if(leadObj.Status__c != status){
            ApexPages.Message errormsg1 = new ApexPages.Message(ApexPages.severity.ERROR,'Please change the lead status to qualified & then try to convert the lead');
            ApexPages.addMessage(errormsg1);
            return null;
        }
We are going to the trouble of writing the code coverage, how about we prove our code does what we expect?
How about a little assert: 
List<Apexpages.Message> msgs = ApexPages.getMessages();
String errorString = 'Please change the lead status to qualified & then try to convert the lead';
//we are in a controlled test class, so there should only be 1 error
System.assertEquals(1,msgs.size());
System.assert(msgs[0].getDetail().contains(errorString));        System.assertEquals(ApexPages.Severity.ERROR,msgs[0].getSeverity());

And if we think deeper, if this method public PageReference convertbutton() is returning a PageRef, why arent we testing in the the test method? We are throwing a null amongst the error handling.
PageReference testPage =   testAccPlan.convertbutton();
System.assertEquals(null,pageRef);
So conversely, in the positive test, why aren't we tsting the returned result?
 
PageReference testPage =   testAccPlan.convertbutton();
System.assertEquals(somestring,pageRef.getUrl());
//OR
System.assert(pageRef.getUrl().contains(someAccount.Id));

Other things to note, why not consider the use of @TestSetup for your test data?

Remember, coverage is only part of the battle for good test code.  Assertions are alos required.

Regards
Andrew