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
KevSnellKevSnell 

Test Method Apex Form Help!

Hi All,

 

I have a simple form with a customer controller which I now need to create the test code so I can deploy to live system, however, I'm havig some issues creating the test method as I'm relatively new to testing.  So I'm hoping someone can help as I can't seem to find the answer anywhere.

 

The VisualForce Page is called New_Reserve_Entry.

 

And here is the Reserve Controller Code:

 

public with sharing class Reserve {
   
    public Lead lead {get; private set;}
   
    public String company {get; set;}
    public String email {get; set;}
    public String phone {get; set;}
    public String firstName {get; set;}
    public String lastName {get; set;}
    public String title {get; set;}
    public string primary_campaign {get; set;}

    public String getName() {
        return 'Reserve';
    }

    // save button is clicked
    public PageReference save() {

        Lead l = new Lead(
        OwnerId = '00GE0000000hCBH',
        LeadSource = 'Reserve',
        FirstName = firstName,
        LastName = lastName,
        Email = email,
        Phone = phone,
        Title = title,
        Company = company,
        );
       
      
    try {
      insert l; // inserts the new record into the database
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,'Error adding Candidate to Reserve List.'));
      return null;
    }
     
        return Page.New_Reserve_Entry_Confirmation;
}

}

@isTest
private with sharing class Reserve_Test {
	
 	public static testMethod void testReserve_Test() {
        PageReference pageRef = Page.New_Reserve_Entry;
        Test.setCurrentPage(pageRef);
      
        reserve controller = new reserve();
        String nextPage = controller.save().getUrl();
              

        //Controller and Data
        controller = new reserve(); 
        Lead l = new Lead(
        OwnerId = '00GE0000000hCBH',
        LeadSource = 'Reserve',
        FirstName = 'FirstName',
        LastName = 'LastName',
        Email = 'test@test.com',
        Phone = '001',
        Title = 'Junior',
        Company = 'Acme'
        );

        //Save
        nextPage = controller.save().getUrl();


        // Verify
        Lead[] leads = [select id, email from lead where Company = 'Mystry'];
        System.assertEquals('firstlast@acme.com', leads[0].email);
        System.assertEquals('lastname',leads[0].LastName);
        
        
    }
		
}

 

So I understand that the test code must call the page, load the controller, insert the lead data, save, confirm return page and check data was inserted.  However, writing it is the problem:

 

I got this far and then got stuck:  Currently I get an error for string nextpage = controller.save().getUrl() saying "Attempt to de-reference a null object"



 

 

 

I would really appreciate if someone could help me out either by fixing the test code, showing me a test code they have for something similar or any links that could help.


Thanks

Kev

 

 

 

 

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Devendra NataniDevendra Natani

Hi,

 

Please try the below code. I have commented out the ownerId beacuse it automatically sets when we create a record.

 

public class Reserve {

    public Lead lead {get; private set;}
    
    public String company {get; set;} 
    public String email {get; set;}
    public String phone {get; set;}
    public String firstName {get; set;}
    public String lastName {get; set;}
    public String title {get; set;} 

    public String getName() {
        return 'Reserve';
    }
   
    // save button is clicked
    public PageReference save() {

        Lead l = new Lead(
        //OwnerId = '00GE0000000hCBH',
        LeadSource = 'Reserve',
        FirstName = firstName,
        LastName = lastName,
        Email = email,
        Phone = phone,
        Title = title,
        Company = company

        );
        
       
    try {
      insert l; // inserts the new record into the database
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,'Error adding Candidate to Reserve List.'));
      return null;
    }
      
        return Page.confirmationReserveEntry; 
        
   }
   
   static testmethod void testReserve()
   {
       Test.startTest();
       Reserve obj = new Reserve();
       obj.company = 'test company';
       obj.email= 'test@test.com';
       obj.phone ='1234567890';
       obj.firstName ='test FN';
       obj.lastName ='test LN';
       obj.title ='test';
       
       system.assert(obj.getName()!=null);
       system.assert(obj.save()!=null);
       Test.stopTest();
   
   }  
}

Please mark this as accepted solution if its working fine. Please let me know if there is any issue. 

 

Thanks,

Devendra Natani

 

All Answers

Devendra NataniDevendra Natani

Hi,

 

There are couple of mistakes in your code. 

  1. Donot set the ownerId hardcoded in save method of class.
  2. In the test method, Create the test data first and set the lead property of controller class. The call the save method.

Please let me know if there is any issue.

 

Thanks,
Devendra Natani

Blog 

KevSnellKevSnell

Thanks for the advice, however, my coding skills are very basic and I really need some help to complete the test method.  Is it possible you could show me what you mean?

 

 

Devendra NataniDevendra Natani

Can you please share the complete of this class?

 

Thanks,

Devendra Natani

KevSnellKevSnell

Here is the Apex Class:

 

public class Reserve {

    public Lead lead {get; private set;}
    
    public String company {get; set;} 
    public String email {get; set;}
    public String phone {get; set;}
    public String firstName {get; set;}
    public String lastName {get; set;}
    public String title {get; set;} 

    public String getName() {
        return 'Reserve';
    }
   
    // save button is clicked
    public PageReference save() {

        Lead l = new Lead(
        OwnerId = '00GE0000000hCBH',
        LeadSource = 'Reserve',
        FirstName = firstName,
        LastName = lastName,
        Email = email,
        Phone = phone,
        Title = title,
        Company = company,

        );
        
       
    try {
      insert l; // inserts the new record into the database
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,'Error adding Candidate to Reserve List.'));
      return null;
    }
      
        return Page.confirmationReserveEntry; 
     
} 

 

KevSnellKevSnell

Also here is the Visualforce Page Code for Reference called New_Reserve_Entry

 

<apex:page controller="Reserve" tabStyle="Upload_Reserve__tab" id="reserve">
      <apex:sectionHeader title="Candidate" subtitle="Upload an Entry"/>
  
  <apex:form id="reserveform">
  
  <apex:pageBlock id="reserveblock" >
          
                  <apex:pageBlockSection title="Candidate Details" collapsible="false" columns="2" id="reserveblocksection">

              
                      <apex:outputlabel for="firstname">First Name</apex:outputlabel>
                      <apex:inputText id="firstname" value="{!firstName}"/>
 
                          
                      <apex:outputlabel for="lastname">Last Name</apex:outputlabel>
                      <apex:define name="reqInputDiv"><div class="reqInput">
                      <apex:define name="reqInputDiv"><div class="reqBlock"/></apex:define>
                      <apex:inputText id="lastname" value="{!lastName}" />
                      </div> 
                      </apex:define>  
                      
                      <apex:outputlabel for="title">Job Title</apex:outputlabel>
                      <apex:inputText value="{!title}"/>
              
                      <apex:outputlabel for="company">Company</apex:outputlabel>
                      <apex:define name="reqInputDiv"><div class="reqInput">
                      <apex:define name="reqInputDiv"><div class="reqBlock"/></apex:define>
                      <apex:inputText id="company" value="{!company}"/>
                      </div> 
                      </apex:define>  
              
                      <apex:outputlabel for="email">Email</apex:outputlabel>
                      <apex:define name="reqInputDiv"><div class="reqInput">
                      <apex:define name="reqInputDiv"><div class="reqBlock"/></apex:define>
                      <apex:inputText id="email" value="{!email}"/>
                      </div>
                      </apex:define>
                      
                      <apex:outputlabel for="phone">Phone</apex:outputlabel>
                      <apex:inputText id="phone" value="{!phone}"/>

                      <apex:commandButton action="{!save}" value="Upload" onclick="validate();"/>
                      
                    
  
  </apex:pageBlockSection>       
          </apex:pageBlock>

</apex:form>

 

Devendra NataniDevendra Natani

Hi,

 

Please try the below code. I have commented out the ownerId beacuse it automatically sets when we create a record.

 

public class Reserve {

    public Lead lead {get; private set;}
    
    public String company {get; set;} 
    public String email {get; set;}
    public String phone {get; set;}
    public String firstName {get; set;}
    public String lastName {get; set;}
    public String title {get; set;} 

    public String getName() {
        return 'Reserve';
    }
   
    // save button is clicked
    public PageReference save() {

        Lead l = new Lead(
        //OwnerId = '00GE0000000hCBH',
        LeadSource = 'Reserve',
        FirstName = firstName,
        LastName = lastName,
        Email = email,
        Phone = phone,
        Title = title,
        Company = company

        );
        
       
    try {
      insert l; // inserts the new record into the database
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,'Error adding Candidate to Reserve List.'));
      return null;
    }
      
        return Page.confirmationReserveEntry; 
        
   }
   
   static testmethod void testReserve()
   {
       Test.startTest();
       Reserve obj = new Reserve();
       obj.company = 'test company';
       obj.email= 'test@test.com';
       obj.phone ='1234567890';
       obj.firstName ='test FN';
       obj.lastName ='test LN';
       obj.title ='test';
       
       system.assert(obj.getName()!=null);
       system.assert(obj.save()!=null);
       Test.stopTest();
   
   }  
}

Please mark this as accepted solution if its working fine. Please let me know if there is any issue. 

 

Thanks,

Devendra Natani

 

This was selected as the best answer
KevSnellKevSnell

Thanks Devendra, now just got to finish some other tests.