I am trying to test my custom controller's saveNewContact() method. I am trying to set the fields on the page, or in the constructor contact, and attempt to save the record. Unfortunately, when I run my test class, My system debug is showing that the constructor's contact last name is null and an error message saying

"Key value cannot be null."

I am thinking that I am not assigning the value to the constructor correctly. I have the following custom controller for a VF page:

public with sharing class DonorSearchCon {
  public Contact con {get;set;}

     public DonorSearchCon() {      
        con = new Contact();
        System.debug('LastName Test: ' +con.LastName);

    public pageReference newExistingContactButton(){
        con.FirstName = result.firstName;

       PageReference newContactRecord = Page.NewContactGMS;
       return newContactRecord;

    public pageReference saveNewContact(){
        if(con.LastName == '' || con.LastName == null){
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.severity.ERROR, 'Please provide Last Name');
            return null;

Test Class:

public static testMethod void testSaveNewContact(){
    donorSearchCon controller = new donorSearchCon();        
    controller = new donorSearchCon();

    Contact cont = new Contact();

   PageReference pageRef = Page.NewContactGMS;
   pageRef.getParameters().put('cont.LastName', 'Test');


VF Page:

   <div class="slds-form-element slds-form-element_horizontal">
      <span class="slds-form-element__label">Last Name</span>
          <div class="slds-form-element__control">
              <abbr class="slds-required" title="required">*</abbr>
                  <apex:inputText value="{! con.LastName }"/>
  • Where are you declaring your con variable in the DonorSearchCon class? Aug 9 '19 at 13:23
  • You must be having a class level attribute for Contact which you must have used in visualforce page, you should assign value to that property in test class. Aug 9 '19 at 13:23

This line is not the correct way to set fields on the Contact:

pageRef.getParameters().put('cont.FirstName', 'Test');

Instead, simply reference the property on your controller:

controller.con.FirstName = 'Test';

Obviously, you would follow the same pattern to set LastName.

  • +1, was trying to understand why he has put that statement from 10 min, :-P Aug 9 '19 at 13:30
  • Thank you for the info. That is what did it. I guess the scenarios on how to test my VF page controller on the net mislead me. Thanks
    – Ivo Dimov
    Aug 9 '19 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.