+ Start a Discussion
Todd B.Todd B. 

Hep setting the value of an inputfield in test class

I have written a basic VF page to view and add phone numbers to a custom object.  The page and the controller work, but I can not figure out the test class.  I am receiving an error message that I am missing a required field.

VF Page:
<apex:page standardController="Task"  extensions="CurrentPhoneRecords_controller" sidebar="false" showHeader="false">
<apex:form >

    <apex:pageBlock >
        <apex:pageBlockSection id="MemberSummary" title="Member Summary" showheader="true" columns="2">
            <apex:outputField value="{!Task.SD_Member_Stakeholders__r.First_Name__c}"/>
            <apex:outputField Label="Age" value="{!Task.SD_Member_Stakeholders__r.Age_SD_Member__c}"/>
            <apex:outputField value="{!Task.SD_Member_Stakeholders__r.Last_Name__c}"/>
            <apex:outputField Label="DOB" value="{!Task.SD_Member_Stakeholders__r.Date_of_Birth__c}"/>
            <apex:outputField value="{!Task.SD_Member_Stakeholders__r.Mailing_Address__c}"/>
            <apex:outputField value="{!Task.SD_Member_Stakeholders__r.Phone_Last_Research_Date__c}"/>   
            <apex:outputField value="{!Task.SD_Member_Stakeholders__r.Mailing_City__c}"/>
            <apex:outputField Label="Click to View Member Record" value="{!Task.WhatId}"/>       
            <apex:outputField value="{!Task.SD_Member_Stakeholders__r.Mailing_State__c}"/>    
            <apex:outputField value="{!Task.SD_Member_Stakeholders__r.Intelius_Search_Link__c}"/>
        </apex:pageBlockSection>
    </apex:pageBlock>
  

<!-- Add a New Phone Number-->
    <apex:actionregion >
        <apex:outputPanel id="AddPhoneNumber" >
            <apex:pageBlock title="Add a New Phone Number" rendered="True">
                <apex:pageBlockButtons location="top" >    <!-- component to contain all the buttons, can show buttons on top, bottom of the record or both -->
                    <apex:commandButton value="New" action="{!newPH}" reRender="AddPhoneNumber" rendered="{!!editPH}"  >
                        <apex:param name="editPH" value="true" assignTo="{!editPH}"/>
                    </apex:commandButton>
                    <apex:commandButton value="Save" action="{!savePH}"  rerender="AddPhoneNumber, PhoneList" rendered="{!editPH}">
                        <apex:param name="SavePH" value="False" assignTo="{!editPH}"/>
                    </apex:commandButton>                    
                    <apex:commandButton value="Save & New" action="{!savenewPH}"  rerender="AddPhoneNumber, PhoneList" rendered="{!editPH}">
                        <apex:param name="SavePH" value="True" assignTo="{!editPH}"/>
                    </apex:commandButton>
<!-- The Cancel Button is not working yet
                    <apex:commandButton value="Cancel" immediate="true" rerender="AddPhoneNumber" rendered="{!editPH}" >
                        <apex:param name="cancelPH" value="false" assignTo="{!editTask}"/>
                    </apex:commandButton>                    
-->
                </apex:pageBlockButtons>
        <apex:pageBlockSection columns="2" >
<!-- View only Fields
           <apex:outputField value="{!ph.Phone_Number__c}" rendered="{!!editPH}" />
           <apex:outputField value="{!ph.Phone_Number_Status__c}" rendered="{!!editPH}" />
           <apex:outputField value="{!ph.Phone_Type__c}" rendered="{!!editPH}" />
-->           
<!-- Add New Phone Number Fields-->
           <apex:inputField value="{!ph.Phone_Number__c}" rendered="{!editPH}" />
           <apex:inputField value="{!ph.Phone_Number_Status__c}" rendered="{!editPH}" />
           <apex:inputField value="{!ph.Phone_Type__c}" rendered="{!editPH}" /> 
         </apex:pageBlockSection>
            </apex:pageBlock>
        </apex:outputPanel>
    </apex:actionregion>

<apex:actionRegion >
    <apex:pageBlock >
        <apex:pageBlockSection id="PhoneList" title="Current Phone Numbers" showHeader="true" columns="1" onclick="saveState(this);">
            <apex:pageBlockTable value="{!PhoneRecords}" var="i" width="100%" border="1" cellspacing="2" cellpadding="2"  >
                <apex:column value="{!i.Phone_Number__c}"/> 
                <apex:column value="{!i.Phone_Number_Status__c}"/> 
                <apex:column value="{!i.Phone_Type__c}"/> 
            </apex:pageBlockTable>
       </apex:pageBlockSection>
    </apex:pageBlock> 
</apex:actionRegion>    

</apex:form>                                        
</apex:page>



Controller:
/*
  Class        : CurrentPhoneRecords
  Developer    : Todd Barry
  Created      : June 1, 2018
  Objective    : Controller for PRM vsiualforce page. 
  Updates      :              
*/

 public class CurrentPhoneRecords_controller {

    Private Task T1;
    Public Phone_Numbers__c PhoneRecords;
    Public boolean editPR {get;set;}                //store boolean variable for making fields editable

    public string sObjectName02 = 'Phone_Numbers__c';//string specifying object name for use in dynamic query
    public string sObjectFields02 {get;set;}         //string that will hold csv of all fields on SDMember
    public string sObjectID02 {get;set;}             //parameter which will be assigned from visualforce page and used to query SDMember with the given ID
    public string sObjectSOQL02 {get;set;}           //string of the complete SOQL query that returns all fields on SDMember
    public string strSDMemberID {get;set;}    
    
    
    public Phone_Numbers__c PH {get;set;}
    public id PHID {get;set;}                        //Phone Number id from SOQL query
    public boolean editPH {get;set;}
    
    public CurrentPhoneRecords_Controller(ApexPages.StandardController controller) {
        this.t1= (Task)Controller.getRecord();        
}
    
                
    
     Public List <Phone_Numbers__c> getPhoneRecords() {
     
        Task t2 = [Select id, whatid from Task where id = :t1.id];  
        strSDMemberID = t2.whatid;       
    
        List <Phone_Numbers__c> PhoneRecords = [Select Id,
                                                Phone_Number__c,
                                                Phone_Number_Status__c,
                                                Phone_Type__c,
                                                Override_Request_Status__c,
                                                SD_Member_Link__c 
                                                From Phone_Numbers__c 
                                                Where SD_Member_Link__c = :t2.whatid];
        return PhoneRecords;                                        
    
    }
    
   Public Void SavePhoneRecords() {
        if(PhoneRecords.id == Null)
            insert PhoneRecords;
        Else
            update Phonerecords; 
    }      
// Adding a new phone number
 public void getPH(){      // retrieve selected task
      
        sObjectFields02 = '';                          //initialize as an emply string to prevent 'null field__c, ...'
        //get the object then get the fields and then field names (returns a list and itterates through it)
        for(string field : schema.getglobaldescribe().get(sObjectName02).getdescribe().fields.getmap().keyset()){
           sObjectFields02 += field + ', ';           //build string of all fields on the given sObject
        }
        sObjectFields02 = sObjectFields02.substring(0,sObjectFields02.length()-2);    //remove the trailing comma
        sObjectFields02+=', lastmodifiedby.name';

        sObjectSOQL02 = 'select ' + sObjectFields02 + ' from ' + sObjectName02 + ' where id = \'' + sObjectId02 +'\'';    //build complete query statement for SDMember which includes all the fields for easy reference
        System.debug (sObjectSOQL02);
        PH = Database.query(sObjectSOQL02);             
 
    }
    
    Public void newPH(){
    PH = New Phone_Numbers__c();
    ph.Phone_Number_Status__c ='Not Called Yet';
    Ph.Phone_Type__c = 'Intelius';
    ph.SD_Member_Link__c = strSDMemberID;

    
    }
    
    public void savePH(){
        if(ph.id == null)         // if new task then insert
            insert PH;
        else
            update PH;            // otherwise update task
    }        
    
        public void savenewPH(){
        if(ph.id == null)         // if new task then insert
            insert PH;
            // Create New PH entry
            PH = New Phone_Numbers__c();
            ph.Phone_Number_Status__c ='Not Called Yet';
            Ph.Phone_Type__c = 'Intelius';
            ph.SD_Member_Link__c = strSDMemberID;
    
    }
         
}

 Test Class:
@isTest
public class TestClass_Outreach_Console_Controller {

    static testMethod void myUnitTest() {
        // TO DO: implement unit test

date dtTestDate  = System.today() + 5;

        // Create User Record 
User u1 = [SELECT Id FROM User Where isActive=True  LIMIT 1];

//Create Service Center
Service_Center__c SC = new Service_Center__c(Name='Test1');
Insert sc;


// Create SD Member Record
SD_Member__c sd = New SD_Member__c(First_Name__c = 'John', 
                                   Last_Name__c = 'Smith', 
                                   Ins_ID_Member__c = '123456', 
                                   Ins_ID_Suscriber__c = '456789',
                                   address__c = '123 Main Street', 
                                   city__c = 'Aster', 
                                   state__c = 'CT', 
                                   zip__c = '06001', 
                                   name = 'John Smith',
                                   Lost_Contact_Follow_Up__c = False,
                                   Mailing_Cycle__c='Week 2.1',
                                   Total_Opt_out__c = False,
                                   Catasys_Stops_Phone_Follow_Ups__c=False,
                                   P10M_Impactable_Cost__c=500,
                                   Work_Phone__c='8607985214',
                                   Member_Eligibility_Status__c='Eligible',
                                   Service_Center__c=sc.id,
                                   Referral_Source__c='Claims Data',
                                   Catasys_Medical_Exclusion_Status__C='Medically Targeted',
                                   Enrollment_Progress_Status__c='Attempting to Contact',
                                   Post_Referral_to_CC_Status__c='Pre Referral',
                                   Carecoach__c = u1.id);
insert sd;

// Create New Phone Record
Phone_Numbers__c phTest = New Phone_Numbers__c(SD_Member_Link__c = sd.id,
                                           Phone_Number__c = '8951239874',
                                           Phone_Type__c = 'Home',
                                           Phone_Number_Status__c = 'Not Called Yet');
insert phTest;        
                                           
        

Task t11 = new Task();
t11.WhatId=sd.id;
t11.Subject = '[Phone Number Research]'; //set the required fields
t11.Status ='In Progress';
t11.ActivityDate = dtTestDate;        
Insert t11;        

Id taskID;
taskID = t11.Id;


 
// Test the currentPhoneRecords_Controller
	ApexPages.StandardController stdController = new ApexPages.StandardController(t11);
        CurrentPhoneRecords_controller cpr = new CurrentPhoneRecords_controller(stdController);
        
        cpr.getPhoneRecords();
        
        cpr.newPH();
        
        cpr.ph.Phone_Number__c = '1234567890';
        
        cpr.savenewPH();
        cpr.savePH();
        
      
    }
}

The issue i am having is with this line:  cpr.ph.Phone_Number__c = '1234567890';.  I am trying to input a new phone number to test the savenewPH and save PH methods.  The error I am receving is System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Phone_Number__c]: [Phone_Number__c] 

How do I set the value of an inputfield in the VF page? 
 
Best Answer chosen by Todd B.
Steven NsubugaSteven Nsubuga
the PH record in cpr.savePH() does not have a phone number. Add a phone number to the PH record created by the cpr.savenewPH(); See below.
 
@isTest
public class TestClass_Outreach_Console_Controller {

    static testMethod void myUnitTest() {
        // TO DO: implement unit test

date dtTestDate  = System.today() + 5;

        // Create User Record 
User u1 = [SELECT Id FROM User Where isActive=True  LIMIT 1];

//Create Service Center
Service_Center__c SC = new Service_Center__c(Name='Test1');
Insert sc;


// Create SD Member Record
SD_Member__c sd = New SD_Member__c(First_Name__c = 'John', 
                                   Last_Name__c = 'Smith', 
                                   Ins_ID_Member__c = '123456', 
                                   Ins_ID_Suscriber__c = '456789',
                                   address__c = '123 Main Street', 
                                   city__c = 'Aster', 
                                   state__c = 'CT', 
                                   zip__c = '06001', 
                                   name = 'John Smith',
                                   Lost_Contact_Follow_Up__c = False,
                                   Mailing_Cycle__c='Week 2.1',
                                   Total_Opt_out__c = False,
                                   Catasys_Stops_Phone_Follow_Ups__c=False,
                                   P10M_Impactable_Cost__c=500,
                                   Work_Phone__c='8607985214',
                                   Member_Eligibility_Status__c='Eligible',
                                   Service_Center__c=sc.id,
                                   Referral_Source__c='Claims Data',
                                   Catasys_Medical_Exclusion_Status__C='Medically Targeted',
                                   Enrollment_Progress_Status__c='Attempting to Contact',
                                   Post_Referral_to_CC_Status__c='Pre Referral',
                                   Carecoach__c = u1.id);
insert sd;

// Create New Phone Record
Phone_Numbers__c phTest = New Phone_Numbers__c(SD_Member_Link__c = sd.id,
                                           Phone_Number__c = '8951239874',
                                           Phone_Type__c = 'Home',
                                           Phone_Number_Status__c = 'Not Called Yet');
insert phTest;        
                                           
        

Task t11 = new Task();
t11.WhatId=sd.id;
t11.Subject = '[Phone Number Research]'; //set the required fields
t11.Status ='In Progress';
t11.ActivityDate = dtTestDate;        
Insert t11;        

Id taskID;
taskID = t11.Id;


 
// Test the currentPhoneRecords_Controller
	ApexPages.StandardController stdController = new ApexPages.StandardController(t11);
        CurrentPhoneRecords_controller cpr = new CurrentPhoneRecords_controller(stdController);
        
        cpr.getPhoneRecords();
        
        cpr.newPH();
        
        cpr.ph.Phone_Number__c = '1234567890';
        
        cpr.savenewPH();

        cpr.ph.Phone_Number__c = '1234567891';
        cpr.savePH();
        
      
    }
}

 

All Answers

Steven NsubugaSteven Nsubuga
the PH record in cpr.savePH() does not have a phone number. Add a phone number to the PH record created by the cpr.savenewPH(); See below.
 
@isTest
public class TestClass_Outreach_Console_Controller {

    static testMethod void myUnitTest() {
        // TO DO: implement unit test

date dtTestDate  = System.today() + 5;

        // Create User Record 
User u1 = [SELECT Id FROM User Where isActive=True  LIMIT 1];

//Create Service Center
Service_Center__c SC = new Service_Center__c(Name='Test1');
Insert sc;


// Create SD Member Record
SD_Member__c sd = New SD_Member__c(First_Name__c = 'John', 
                                   Last_Name__c = 'Smith', 
                                   Ins_ID_Member__c = '123456', 
                                   Ins_ID_Suscriber__c = '456789',
                                   address__c = '123 Main Street', 
                                   city__c = 'Aster', 
                                   state__c = 'CT', 
                                   zip__c = '06001', 
                                   name = 'John Smith',
                                   Lost_Contact_Follow_Up__c = False,
                                   Mailing_Cycle__c='Week 2.1',
                                   Total_Opt_out__c = False,
                                   Catasys_Stops_Phone_Follow_Ups__c=False,
                                   P10M_Impactable_Cost__c=500,
                                   Work_Phone__c='8607985214',
                                   Member_Eligibility_Status__c='Eligible',
                                   Service_Center__c=sc.id,
                                   Referral_Source__c='Claims Data',
                                   Catasys_Medical_Exclusion_Status__C='Medically Targeted',
                                   Enrollment_Progress_Status__c='Attempting to Contact',
                                   Post_Referral_to_CC_Status__c='Pre Referral',
                                   Carecoach__c = u1.id);
insert sd;

// Create New Phone Record
Phone_Numbers__c phTest = New Phone_Numbers__c(SD_Member_Link__c = sd.id,
                                           Phone_Number__c = '8951239874',
                                           Phone_Type__c = 'Home',
                                           Phone_Number_Status__c = 'Not Called Yet');
insert phTest;        
                                           
        

Task t11 = new Task();
t11.WhatId=sd.id;
t11.Subject = '[Phone Number Research]'; //set the required fields
t11.Status ='In Progress';
t11.ActivityDate = dtTestDate;        
Insert t11;        

Id taskID;
taskID = t11.Id;


 
// Test the currentPhoneRecords_Controller
	ApexPages.StandardController stdController = new ApexPages.StandardController(t11);
        CurrentPhoneRecords_controller cpr = new CurrentPhoneRecords_controller(stdController);
        
        cpr.getPhoneRecords();
        
        cpr.newPH();
        
        cpr.ph.Phone_Number__c = '1234567890';
        
        cpr.savenewPH();

        cpr.ph.Phone_Number__c = '1234567891';
        cpr.savePH();
        
      
    }
}

 
This was selected as the best answer
Todd B.Todd B.
Thanks Steven, I always get tripped up on the easy stuff!