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
Megan Moody 10Megan Moody 10 

Need help with test class for *simple* Apex class & VF page

I am a newbie at development. I have an Apex class and a Visualforce page that I need test coverage for. I just can't get complete code coverage. Any help in getting me closer to 100% code coverage for this is very much appreciated!

My Apex class:
public class ConciergeDisplayFamilyMembers
{ 
    public Contact currentContact {get;set;}     
    
    // Get Record Type ID for EE Consumer Contact records
       RecordType rtee = [select id from RecordType where SobjectType='Contact' and Name='EE Consumer' Limit 1];
    
    public List<Contact> Records
    {
        
        get
        {
            try
            {
                Records = new List<Contact>();
                Records =   [
                            SELECT Name,Gender__c,Subscriber_ID__c,Member_ID_suffix__c,Member_ID__c 
                            FROM Contact 
                            WHERE Subscriber_ID__c = :currentContact.Subscriber_ID__c
                               and Subscriber_ID__c != null
                               and Health_Plan__c = :currentContact.Health_Plan__c
                               and RecordTypeId = :rtee.id
                            ORDER BY Member_ID_suffix__c
                            ]; 
            } 
            catch (Exception ex)
            {
                  Records = null;
            }
            return Records;
        }
        private set;
    }
        

    public ConciergeDisplayFamilyMembers(ApexPages.StandardController sc)
    {
        if(!Test.isRunningTest()){
        sc.AddFields(new List<String>{'Subscriber_ID__c'});
        sc.AddFields(new List<String>{'Health_Plan__c'});
        currentContact = (Contact) sc.getRecord();     
        System.debug('***** ' + currentContact );
            }
    }

}


My Visualforce page:
<apex:page standardController="Contact" extensions="ConciergeDisplayFamilyMembers">
<style>
    span.EmployerIneligible
        {background-color:red; font-size:125%; font-weight:bold;}

    span.EmployeeEligible
        {background-color:#00FF00; font-size:125%; font-weight:bold;}    

    span.EmployeeIneligible
        {background-color:orange; font-size:125%; font-weight:bold;}
        
    span.CoverageDates
        {font-size:110%; font-weight:bold;}

        
</style>

<apex:pageBlock >

<apex:panelGrid >
    <apex:outputPanel rendered="{!Contact.Service_Status__c == 'Employer Not Eligible'}">
        <span class="EmployerIneligible">{!Contact.Service_Status__c}</span>
        
    </apex:outputPanel>
    
    <apex:outputPanel rendered="{!Contact.Service_Status__c == 'Employee Not Eligible'}">
        <span class="EmployeeIneligible">{!Contact.Service_Status__c}</span>
        <span class="CoverageDates">
                <apex:outputText value="{0, date, M'/'d'/'yyyy}">
                    <apex:param value="{!Contact.Coverage_Start_Date__c}" /> 
                </apex:outputText>
                <apex:outputText > - </apex:outputText>
                <apex:outputText value="{0, date, M'/'d'/'yyyy}">
                    <apex:param value="{!Contact.Coverage_End_Date__c}" /> 
                </apex:outputText>
              
        </span>    

    </apex:outputPanel>
    
    <apex:outputPanel layout="block" rendered="{!Contact.Service_Status__c == 'Eligible'}">
        <apex:panelGrid columns="2">
            <span class="EmployeeEligible">{!Contact.Service_Status__c}</span>
        
            
                <apex:outputText ><span class="CoverageDates">Days since last activity: &nbsp;&nbsp;&nbsp; <apex:outputField value="{!Contact.Days_Since_Last_Activity__c}"/></span></apex:outputText> 
            
            

            <apex:Outputtext ><b>HS Products:&nbsp;&nbsp;&nbsp;</b></apex:Outputtext>
            <apex:outputText ><p id="demo"></p></apex:outputText>
            
            
        </apex:panelGrid>
    </apex:outputPanel>
</apex:panelGrid>
 
</apex:pageBlock>

    <apex:pageBlock title="Family Members"> 
        <apex:pageBlockTable value="{!Records}" var="Record" > 
            <apex:column > 
                <apex:facet name="header">Name</apex:facet> 
                <apex:outputLink target="_self" value="{!Record.ID}">{!Record.Name}</apex:outputlink>
            </apex:column> 
            <apex:column > 
                <apex:facet name="header">Member ID</apex:facet> 
                <apex:outputText value="{!Record.Member_ID__c}"/> 
            </apex:column>
            <apex:column > 
                <apex:facet name="header">suffix</apex:facet> 
                <apex:outputText value="{!Record.Member_ID_suffix__c}"/> 
            </apex:column>  
            <apex:column > 
                <apex:facet name="header">Gender</apex:facet> 
                <apex:outputText value="{!Record.Gender__c}"/> 
            </apex:column> 
            <apex:column > 
                <apex:facet name="header">Subscriber ID</apex:facet> 
                <apex:outputText value="{!Record.Subscriber_ID__c}"/> 
            </apex:column> 
        </apex:pageBlockTable> 
    </apex:pageBlock>
    
    
        
        <apex:relatedList list="Cases"/>
        
    

<script>
    var myString = '{!Contact.Account.Concierge_HS_Products__c}';
    var res = myString.replace(new RegExp(';', 'g'), '<br/>');
    document.getElementById("demo").innerHTML =res;       
</script>


</apex:page>
Here's the test class I've written. It only gets 23% code coverage:
@isTest
private class TestConciergeDisplayFamilyMembers{


    public static testmethod void testConciergeDisplayFamilyMembers(){
        
        // Get Record Type ID for EE Consumer Contact records
       RecordType rtee = [select id from RecordType where SobjectType='Contact' and Name='EE Consumer' Limit 1];
      RecordType rthp = [select id from RecordType where SobjectType='Account' and Name='Customer - Health Plan' Limit 1];
      RecordType rtemp = [select id from RecordType where SobjectType='Account' and Name='Customer - Employer' Limit 1];
        
        //Create Employer Account
        Account objAccount = New Account();
        objAccount.Name = 'Test Employer Account';
        objAccount.Type = 'Customer';
        objAccount.Customer_Type__c = 'Employer'; 
        objAccount.RecordTypeId = rtemp.id;
        objAccount.generated_from_leads__c = true;
        Insert objAccount;
    
        Account empAccount = objAccount;
        
        //Create Health Plan Account
        Account objAccountHP = New Account();
        objAccountHP.Name = 'Test Health Plan';
        objAccountHP.Type = 'Customer';
        objAccount.Customer_Type__c = 'Health Plan'; 
        objAccountHP.RecordTypeId = rthp.id;
        objAccountHP.generated_from_leads__c = true;
        Insert objAccountHP;
        
        Account hpAccount = objAccountHP;
        
        //Create Contacts with same subscriber number
        List<Contact> objContact = new List<Contact>();
        for (integer j=0;j<3;j++){
             objContact.add(new Contact(FirstName='Test' + j,
                                 LastName='Test' +j,
                                AccountId= empAccount.Id,
                                Subscriber_ID__c = '11111',
                                RecordTypeId = rtee.id,
                                Health_Plan__c = hpAccount.Id,
                                Member_ID__c = '1'));
                    }
        insert objContact;
        
        //Create Contacts with different subscriber number
        List<Contact> objContact2= new List<Contact>();
        for (integer j=10;j<15;j++){
             objContact2.add(new Contact(FirstName='Test' + j,
                                 LastName='Test' +j,
                                AccountId= objAccount.Id,
                                Subscriber_ID__c = '1234',
                                RecordTypeId = rtee.id,
                                Health_Plan__c = objAccountHP.Id,
                                Member_ID__c = '1'));
          }
        insert objContact2;
        
        //Get the ID of the first contact created
        Contact firstContact = [SELECT ID, firstname,Subscriber_ID__c, Member_ID__c FROM Contact WHERE ID = :objContact[0].Id];
        system.debug('first contact: ' + firstContact.ID + ' ' + firstContact.FirstName);
          
        PageReference myVfPage = Page.Concierge_Service_Status;
        Test.setCurrentPage(myVfPage);
        ConciergeDisplayFamilyMembers testFamily = new ConciergeDisplayFamilyMembers(new ApexPages.StandardController(firstContact));
        ApexPages.StandardController sc = new ApexPages.StandardController(firstContact);
          //ConciergeDisplayFamilyMembers testFamily = new ConciergeDisplayFamilyMembers(sc);
        Contact primaryContact = testFamily.currentContact;
        }

}
 
Best Answer chosen by Megan Moody 10
Amit Chaudhary 8Amit Chaudhary 8
Please try below test class. I hope that will help you.
@isTest
private class TestConciergeDisplayFamilyMembers
{
    public static testmethod void testConciergeDisplayFamilyMembers()
	{
        
		// Get Record Type ID for EE Consumer Contact records
		RecordType rtee = [select id from RecordType where SobjectType='Contact' and Name='EE Consumer' Limit 1];
		RecordType rthp = [select id from RecordType where SobjectType='Account' and Name='Customer - Health Plan' Limit 1];
		RecordType rtemp = [select id from RecordType where SobjectType='Account' and Name='Customer - Employer' Limit 1];
        
        //Create Employer Account
        Account objAccount = New Account();
        objAccount.Name = 'Test Employer Account';
        objAccount.Type = 'Customer';
        objAccount.Customer_Type__c = 'Employer'; 
        objAccount.RecordTypeId = rtemp.id;
        objAccount.generated_from_leads__c = true;
        Insert objAccount;
    
        Account empAccount = objAccount;
		Account objAccountHP = New Account();
        objAccountHP.Name = 'Test Health Plan';
        objAccountHP.Type = 'Customer';
        objAccount.Customer_Type__c = 'Health Plan'; 
        objAccountHP.RecordTypeId = rthp.id;
        objAccountHP.generated_from_leads__c = true;
        Insert objAccountHP;
        
        Account hpAccount = objAccountHP;
		
        //Create Contacts with same subscriber number
        List<Contact> objContact = new List<Contact>();
        for (integer j=0;j<3;j++)
		{
             objContact.add(new Contact(FirstName='Test' + j,
                                 LastName='Test' +j,
                                AccountId= empAccount.Id,
                                Subscriber_ID__c = '11111',
                                RecordTypeId = rtee.id,
                                Health_Plan__c = hpAccount.Id,
                                Member_ID__c = '1'));
        }
        insert objContact;
        
        //Create Contacts with different subscriber number
        List<Contact> objContact2= new List<Contact>();
        for (integer j=10;j<15;j++)
		{
             objContact2.add(new Contact(FirstName='Test' + j,
                                 LastName='Test' +j,
                                AccountId= objAccount.Id,
                                Subscriber_ID__c = '1234',
                                RecordTypeId = rtee.id,
                                Health_Plan__c = objAccountHP.Id,
                                Member_ID__c = '1'));
        }
        insert objContact2;
        
        //Get the ID of the first contact created
        Contact firstContact = [SELECT ID, firstname,Subscriber_ID__c, Member_ID__c FROM Contact WHERE ID = :objContact[0].Id];
        system.debug('first contact: ' + firstContact.ID + ' ' + firstContact.FirstName);
          
        PageReference myVfPage = Page.Concierge_Service_Status;
        Test.setCurrentPage(myVfPage);
        ApexPages.StandardController sc = new ApexPages.StandardController(firstContact);
        ConciergeDisplayFamilyMembers testFamily = new ConciergeDisplayFamilyMembers(sc);
		testFamily.currentContact = firstContact;
		
		List<Contact> LstRecords = testFamily.Records;
		
        }

}

If possible then please remove below if condition from main class.
if(!Test.isRunningTest())

Please check below post for more information on test classes:-
http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html
Please let us know if  this will help you.

Thanks,
Amit Chaudhary

All Answers

Terence_ChiuTerence_Chiu
Hi Megan, on line 38 of your controller class you have an if condition that checks if a test is not running. When the test class is running that condition will evaluate to FALSE which means the code within that if branch will not run during test execution. Any reason why you have that if condition ?
Megan Moody 10Megan Moody 10
If I don't wrap that statement with the IF statement excluding it, I get the error:
System.SObjectException: You cannot call addFields when the data is being passed into the controller by the caller.

The issue is described here: Best Practice: Related Fields with Standard Controller Extensions (http://raydehler.com/cloud/clod/best-practice-related-fields-with-standard-controller-extensions.html). Also described there is a fix so don't have to not use that code. I implemented that fix and I'm now up to a whopping 28% code coverage. 

So my new Apex code is the same as what I posted above, except that I've changed lines 36 - 46 to be:
public ConciergeDisplayFamilyMembers(ApexPages.StandardController sc)
    {
        currentContact = (Contact) sc.getRecord();     
    }
}
And I added the following lines of code to the VF page:
 
<apex:outputField rendered="false" value="{!Contact.Subscriber_ID__c}"/>
<apex:outputField rendered="false" value="{!Contact.Health_Plan__c}"/>

According to the Developer Console, the following lines of code within the Apex class are not being covered by my unit test:
8
13
15
16
19
21
22
27
28
29
30

The lines that are being covered in by my test class are;
3
6
36
40
 
Amit Chaudhary 8Amit Chaudhary 8
Please try below test class. I hope that will help you.
@isTest
private class TestConciergeDisplayFamilyMembers
{
    public static testmethod void testConciergeDisplayFamilyMembers()
	{
        
		// Get Record Type ID for EE Consumer Contact records
		RecordType rtee = [select id from RecordType where SobjectType='Contact' and Name='EE Consumer' Limit 1];
		RecordType rthp = [select id from RecordType where SobjectType='Account' and Name='Customer - Health Plan' Limit 1];
		RecordType rtemp = [select id from RecordType where SobjectType='Account' and Name='Customer - Employer' Limit 1];
        
        //Create Employer Account
        Account objAccount = New Account();
        objAccount.Name = 'Test Employer Account';
        objAccount.Type = 'Customer';
        objAccount.Customer_Type__c = 'Employer'; 
        objAccount.RecordTypeId = rtemp.id;
        objAccount.generated_from_leads__c = true;
        Insert objAccount;
    
        Account empAccount = objAccount;
		Account objAccountHP = New Account();
        objAccountHP.Name = 'Test Health Plan';
        objAccountHP.Type = 'Customer';
        objAccount.Customer_Type__c = 'Health Plan'; 
        objAccountHP.RecordTypeId = rthp.id;
        objAccountHP.generated_from_leads__c = true;
        Insert objAccountHP;
        
        Account hpAccount = objAccountHP;
		
        //Create Contacts with same subscriber number
        List<Contact> objContact = new List<Contact>();
        for (integer j=0;j<3;j++)
		{
             objContact.add(new Contact(FirstName='Test' + j,
                                 LastName='Test' +j,
                                AccountId= empAccount.Id,
                                Subscriber_ID__c = '11111',
                                RecordTypeId = rtee.id,
                                Health_Plan__c = hpAccount.Id,
                                Member_ID__c = '1'));
        }
        insert objContact;
        
        //Create Contacts with different subscriber number
        List<Contact> objContact2= new List<Contact>();
        for (integer j=10;j<15;j++)
		{
             objContact2.add(new Contact(FirstName='Test' + j,
                                 LastName='Test' +j,
                                AccountId= objAccount.Id,
                                Subscriber_ID__c = '1234',
                                RecordTypeId = rtee.id,
                                Health_Plan__c = objAccountHP.Id,
                                Member_ID__c = '1'));
        }
        insert objContact2;
        
        //Get the ID of the first contact created
        Contact firstContact = [SELECT ID, firstname,Subscriber_ID__c, Member_ID__c FROM Contact WHERE ID = :objContact[0].Id];
        system.debug('first contact: ' + firstContact.ID + ' ' + firstContact.FirstName);
          
        PageReference myVfPage = Page.Concierge_Service_Status;
        Test.setCurrentPage(myVfPage);
        ApexPages.StandardController sc = new ApexPages.StandardController(firstContact);
        ConciergeDisplayFamilyMembers testFamily = new ConciergeDisplayFamilyMembers(sc);
		testFamily.currentContact = firstContact;
		
		List<Contact> LstRecords = testFamily.Records;
		
        }

}

If possible then please remove below if condition from main class.
if(!Test.isRunningTest())

Please check below post for more information on test classes:-
http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html
Please let us know if  this will help you.

Thanks,
Amit Chaudhary
This was selected as the best answer
Megan Moody 10Megan Moody 10
That WORKED!!! Thank you so much! I truly appreciate it.