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
cashworthcashworth 

Need Help with Test Methods for Class and Visualforce Page

Hoping to get some guidance and maybe lift the fog I seem to be in with understanding test methods for Apex Classes. I have gotten the test methods for triggers down fairly well but am still struggling with getting coverage on my classes that query records and return them to visualforce pages dynamically. I have 3 classes/VF pages that are plaguing me on coverage at the moment. The first is listed below. Any examples and/or recommendations would be appreciated.

 

Lead Inbox:

This is a Class and VF page that we created as a home page component. It returns and displays unread leads for our users filters by lead source so that they can be aware of new Leads assigned to them that need their attention. The class and page is designed to get the leads and also return a count of how many unread leads they have. I have used sharing on this class as the lists generated need to be specific to the rep or manager viewing the inbox on their homepage. I also have a reference to a sorting class on here that allows the reps to sort the list in the VF page.

 

Here's the class. The code works perfectly but I currently have 0% coverage as I have no test method on it.

 

public with sharing class LeadInbox {


 
public PageReference ViewData() {
return null;
}

List<Lead> rqs;
public String sortField {get; set;}
public String previousSortField {get; set;}

 public List<Lead> getLead() {

  if(rqs == null){
  rqs = [select Id, Name, Company, LeadSource, Status, OwnerId, CreatedDate from Lead 
  
  Where (
  (LeadSource='Partner Referral'
   OR
  LeadSource='Employee Referral'
   OR
  LeadSource='External Referral Program'
   OR
  LeadSource='Management Networking'
   OR
  LeadSource='Sales Inquiry (Web)'
   OR
  LeadSource='Telemarketing'
  )

  AND
  IsUnreadByOwner = TRUE
  AND
  Status != 'Disqualified')
  ORDER BY Lead.CreatedDate Desc
  Limit 4 ];
  }
  return  rqs;
 }


public void doSort(){
        String order = 'asc';
        
        /*This checks to see if the same header was click two times in a row, if so 
        it switches the order.*/
        if(previousSortField == sortField){
            order = 'desc';
            previousSortField = null;
        }else{
            previousSortField = sortField;
        }
       
        //To sort the table we simply need to use this one line, nice!
        superSort.sortList(rqs,sortField,order);
    }


public Integer getUnreadLeads() {

return [

select count() from Lead

where (IsConverted = False
 AND 
  IsUnreadByOwner = TRUE
 AND
  Status != 'Disqualified'
 AND
  (LeadSource ='Partner Referral'
   OR
  LeadSource='Employee Referral'
   OR
  LeadSource='External Referral Program'
   OR
  LeadSource='Management Networking'
   OR
  LeadSource='Sales Inquiry (Web)'
   OR
  LeadSource='Telemarketing'
  )

];

}

 

and the VF page: It works perfectly as well. :) 

 

<apex:page cache="true" controller="LeadInbox" tabStyle="Lead" showHeader="false">
<html>

<body>

<apex:form id="test">
  <apex:pageblock title="">

    <table width="100%" border="0" cellpadding="0" cellspacing="0">
        <tr>     
             <td width="13%" height="120">
              
                 <table>
                 
 <tr><td align="center"><font size="5" color="#0000CC"><a href="/00Q?fcf=00B30000005veVy" target="_parent"><b>{!UnreadLeads}</b></a></font></td></tr>                
 <tr><td align="center"> <font size="3" color="#0000CC">Unread Referral Leads</font></td></tr>
                    
                 </table>       
            </td>
    
            <td width="87%">
        <apex:pageBlockTable value="{!Lead}" var="L" id="table">
                                               
            <apex:column >
                <apex:facet name="header">Action</apex:facet>
                <apex:outputLink title="" value="/{!L.id}" target="_blank" style="font-weight:bold">View</apex:outputLink>&nbsp;        
            </apex:column>    
            
           <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="{!$ObjectType.Lead.Fields.Name.Label}" action="{!doSort}" rerender="table">
                            <apex:param name="sortField" value="Name" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!L.Name}"/>
                </apex:column>

            
           <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="{!$ObjectType.Lead.Fields.Company.Label}" action="{!doSort}" rerender="table">
                            <apex:param name="sortField" value="Company" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!L.Company}"/>
                </apex:column>
            
            <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="{!$ObjectType.Lead.Fields.LeadSource.Label}" action="{!doSort}" rerender="table">
                            <apex:param name="sortField" value="LeadSource" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!L.LeadSource}"/>
                </apex:column>
            
            <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="{!$ObjectType.Lead.Fields.Status.Label}" action="{!doSort}" rerender="table">
                            <apex:param name="sortField" value="Status" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!L.Status}"/>
                </apex:column>
            
            <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="{!$ObjectType.Lead.Fields.OwnerId.Label}" action="{!doSort}" rerender="table">
                            <apex:param name="sortField" value="OwnerId" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!L.OwnerId}"/>
                </apex:column>
            
            <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="{!$ObjectType.Lead.Fields.CreatedDate.Label}" action="{!doSort}" rerender="table">
                            <apex:param name="sortField" value="CreatedDate" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!L.CreatedDate}"/>
                </apex:column>
            
        </apex:pageBlockTable>
        
      </td>
      
     </tr>   
    </table>    
        
  </apex:pageblock>
    
</apex:form>

</body>
</html>
</apex:page>

Any help on developing a test method on this would be appreciated. Its just a query and page render so I know its can't be THAT complicated. I have read through all the documentation on writing test methods and something about it for classes just doesn't make sense to me.

 

Best Answer chosen by Admin (Salesforce Developers) 
Pradeep_NavatarPradeep_Navatar

Tryout this sample code of testclass :

 

@isTest

          private class TestLeadInbox

         {

                static testMethod void testrunmethod()

                {                             

                 LeadInbox  ln = new LeadInbox();

                ln.ViewData();

                 Lead l = new Lead(name='leaddata',company='nav',Leadsource='Partner Referral',IsConverted = false,IsUnreadByOwner = true,Status = 'qualified');

                insert l;

                ln.getLead();

                ln.previousSortField = 'value1';

                ln.sortField = 'value1'

                ln.doSort();

                ln.getUnreadLeads();

                }

         }

 

Hope this helps.

All Answers

frederic baudaxfrederic baudax

Hi,

 

Test methods for VF page controllers/extensions works slightly differently than for triggers, hereby a sample to demonstrate how you can achieve this.

 

 

// first insert your leads as you would do in a bulk insert test method, of course matching your query criteria’s 

//then you will need to call your page and the extension, I’ve read somewhere that in your case you would not need to create the page but never had to test this myself 

//instantiate the page as if you were navigating to it
PageReference pageRef = Page.YOURVFPAGE;

//in case you need to add parameters to you URL you can use the getParameters().put(id,value)
pageRef.getParameters().put('id', e.id);
Test.setCurrentPageReference(pageRef);

//Create an instance of the controller/extension and call the functions.
/*usually you will have to use something like this, instantiate both + pass the record you will need for your tests  
ApexPages.StandardController e = new ApexPages.StandardController(new Event());
Customextention Ext = new Customextention(e);
*/
//in your case, only testing extention + no record to pass on
LeadInbox Ext = new LeadInbox(); //test your functions to reach the coverage Ext.ViewData(); Ext.doSort(); Ext.getUnreadLeads();

 

Cheers,

Fred

Pradeep_NavatarPradeep_Navatar

Tryout this sample code of testclass :

 

@isTest

          private class TestLeadInbox

         {

                static testMethod void testrunmethod()

                {                             

                 LeadInbox  ln = new LeadInbox();

                ln.ViewData();

                 Lead l = new Lead(name='leaddata',company='nav',Leadsource='Partner Referral',IsConverted = false,IsUnreadByOwner = true,Status = 'qualified');

                insert l;

                ln.getLead();

                ln.previousSortField = 'value1';

                ln.sortField = 'value1'

                ln.doSort();

                ln.getUnreadLeads();

                }

         }

 

Hope this helps.

This was selected as the best answer
cashworthcashworth

Thanks for the help guys! I think I get it now. I took the code example and the detailed explanation provided by you two and now have 100% coverage for my class. Better yet I understand what I was NOT doing before that was causing my coverage to be nonexistent for my controllers classes.

 

Again, thanks a bunch. Below is the final test method proviing 100% coverage:

 

 

static testMethod void testrunmethod()
                {                      
              LeadInbox  ln = new LeadInbox();
                ln.ViewData();               
                                
              Lead l1 = new Lead(lastname='leaddata',company='nav',Leadsource='Telemarketing',IsConverted = false,IsUnreadByOwner = true,Status = 'qualified');
                insert l1;
              Lead l2 = new Lead(lastname='leaddata',company='nav',Leadsource='Management Networking',IsConverted = false,IsUnreadByOwner = true,Status = 'qualified');
                insert l2;  
                
                ln.getUnreadLeads();
                integer i = 1;
                system.assert(ln.getUnreadLeads() > i);
                
                ln.getLead();
                ln.sortfield = null;
                ln.previousSortField = null;
                ln.sortField = 'company';
                ln.doSort();
                
                ln.previousSortField = 'company';
                ln.doSort();
                
                ln.sortfield = 'Status';                              
                ln.doSort();