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
Glenn at MvistaGlenn at Mvista 

Test Class for public VisualForce Pages

I have created a webpage that we use to capture Mutual NDA information from prospects to create a Contract object in Salesforce.  It works fine, but my problem is I have 0% code coverage and do not even know where to begin.  Can someone help me (note I have looked at the VisualForce documents but they are not completely clear).  I am hoping for a pointer, not a full test class (but a full test class would not be unappreciated :).  Here is the page and the Controller.

<apex:page controller="Contract_WebSubmitPageReference" standardStylesheets="true" showHeader="false" sidebar="false">
<apex:form >
    <apex:pageBlock >
        <table cellspacing="2" cellpadding="2">
            <tr><td width="100" align="center" valign="center">
                <apex:image url="{!$Resource.logo}" width="82" height="74"/>
            </td><td>
                <h1><font size="+2">Request a Mutual NDA with MontaVista Software, LLC</font></h1>
            </td></tr>
        </table>
        <apex:pageBlockSection columns="1" > 
      <hr/>
      <p>
      <i><b>NOTE:</b> If you wish to enter anything other than the accepted options in the Contract Details section below, you cannot use this webform to request an NDA and you need to get in touch with your MontaVista contact to initiate a custom version of our Mutual NDA.</i>
        </p>
        <hr/>
          <p>
          Please describe who you are and why you are requesting a Mutual NDA at this time.  Include any names of MontaVista Employees with whom you are in contact.
          </p>
            <apex:inputField value="{!contract.Description}" style="height:100px;width:300px;" label="Explanation of Request"/> 
          <h2>Your Contact Information</h2>
            <apex:inputField value="{!contract.Requestor_First_Name__c}" label="First Name" required="true"/>
            <apex:inputField value="{!contract.Requestor_Last_Name__c}" label="Last Name" required="true"/>
            <apex:inputField value="{!contract.Requestor_Title__c}" label="Title" required="true"/>
            <apex:inputField value="{!contract.Requestor_Email__c}" label="Business Email Address" required="true"/>
            <apex:inputField value="{!contract.Requestor_Phone__c}" label="Phone Number"/>
        <h2>Legal Company Name and Corporate Address</h2>
            <apex:inputField value="{!contract.Customer_Name__c}" label="Full Company Name" required="true"/>
            <apex:inputField value="{!contract.Contract_Street__c}" label="Street Address" required="true"/>
            <apex:inputField value="{!contract.Contract_City__c}" label="City" required="true"/>
            <apex:inputField value="{!contract.Contract_State__c}" label="State/Province" required="true"/>
            <apex:inputField value="{!contract.Contract_Postal_Code__c}" label="Postal Code" required="true"/>
            <apex:inputField value="{!contract.Contract_Country__c}" label="Country" required="true"/>
        <hr/>
        <h2>Contract Details</h2>
            <apex:outputText value="The duration can be between 1 and 5 years for our standard Mutual NDA."/>
            <apex:inputField value="{!contract.Duration__c}" label="Duration" required="true"/>
            <apex:outputText value="This state selected here shall govern this Agreement and any dispute arising under this Agreement. You can select Califoria or Delaware as the jurisdction."/>
            <apex:inputField value="{!contract.Govern_Law__c}" label="Governing Law" required="true"/> 
        <hr/>
        <p align="center">
        &copy; 2012 MontaVista Software, LLC. All Rights Reserved &bull; <a href="http://www.mvista.com/privacy_policy.php" target="blank">Privacy Policy</a>
        </p>
        </apex:pageBlockSection>
        <apex:commandButton action="{!save}" value="Request Contract"/>
    </apex:pageBlock> 
</apex:form>
</apex:page>


Controller:

public class Contract_WebSubmitPageReference {
    Contract contract;

    public Contract getContract() {
        if(contract == null) contract = new Contract();
        return contract;
    }

    public PageReference save() {
        // Add the contract to the database.  

                if (contract.AccountId == null) {

                List<Account> acctId = [select Id from Account where Name =: contract.Customer_Name__c limit 1];
                        string aId;
                        if (acctId.isEmpty() == false) { 
                                aId = acctId[0].Id;
                                contract.AccountId = aId;
                        } else {
                                Account a = new Account();
                                        a.Name = contract.Customer_Name__c;
                                        a.BillingStreet = contract.Contract_Street__c;
                                        a.BillingCity = contract.Contract_City__c;
                                        a.BillingState = contract.Contract_State__c;
                                        a.BillingPostalCode = contract.Contract_Postal_Code__c;
                                        a.BillingCountry = contract.Contract_Country__c;
                                        insert a;
                                aId = a.Id;
                                contract.AccountId = aId;
                        } 
                if (contract.CustomerSignedId == null) {

                List<Contact> conId = [select Id from Contact where Email =: contract.Requestor_Email__c limit 1];
                        string cId;
                        if (conId.isEmpty() == false) { 
                                cId = conId[0].Id;
                                contract.Primary_Contact__c = cId;
                                contract.CustomerSignedId = cId;
                        } else {
                                Contact c2 = new Contact();
                                        c2.FirstName = contract.Requestor_First_Name__c;
                                        c2.LastName = contract.Requestor_Last_Name__c;
                                        c2.Title = contract.Requestor_Title__c;
                                        c2.Email = contract.Requestor_Email__c;
                                        c2.Phone = contract.Requestor_Phone__c;
                                        c2.AccountId = aId;
                                        insert c2;
                                cId = c2.Id;
                                contract.Primary_Contact__c = cId;
                                contract.CustomerSignedId = cId;
                        }
                } 
                contract.Status = 'Draft';
                contract.Source__c = 'Web Form';
                contract.StartDate = date.today();
                contract.Type__c = 'Mutual NDA';
                contract.RecordTypeId = [Select Id From RecordType where sObjectType='Contract' and isActive=true and Name='Mutual NDA'].Id;
        contract.Name = date.today().year() + ' - ' + contract.Customer_Name__c + ' - Mutual NDA';
                }
        insert contract;

        
                // Submit for Approval by Legal.
        Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
                req1.setComments('Submitting request for approval via the Web Form.');
                req1.setObjectId(contract.id);
        Approval.ProcessResult result = Approval.process(req1);


        // Send the user to the detail page for the new account. 
    
        PageReference acctPage = new PageReference('http://www.mvista.com');
        acctPage.setRedirect(true);
        return acctPage;
    }
}


Best Answer chosen by Glenn at Mvista
pconpcon
The problem is that your page has nothing to do with your tests.  Unfortunately all of the controller testing has to be done manually.  So for this your test should look like

static testmethod void testCPDownloadGroup() {
     Product_Group__c pg = new Product_Group__c(
          Name='TestGroup', 
          Active__c = true, 
          Release_Images__c = 'www.cnet.com',
          Updates_and_Fixes__c = 'www.google.com'
     );
     insert pg;

     PageReference pageRef = new PageReference('/apex/CP_DownloadGroup?groupid=' + pg.Id          );

     CPDownloadGroup controller = new CPDownloadGroup();
     System.Test.setCurrentPage(pageRef);
     ApexPages.currentPage().getParameters().put('groupid', pg.Id);

     Test.startTest();

     Product_Group__c result = controller.getpg();

     Test.stopTest();

     System.assertEquals(pg.Id, result.Id);
}

You'll probably want to think about doing some additional error checking in your getpg method in case the groupid parameter is not set or if Product_Group__c does not exist.

All Answers

pconpcon
Just to clarify some of your language, you do not test the VisualForce page, you only test the controller.  This is done just like normal apex testing with the exception of using the Test.setCurrentPage method. This link should give you enough information to get started on your testing [1].  If you have any specific questions about your tests after reviewing this documentation, please feel free to ask.

[1] http://www.salesforce.com/us/developer/docs/pages/Content/pages_controller_error_handling.htm
Glenn at MvistaGlenn at Mvista
pcon, thanks, and you are correct on testing the controller not the page, sorry about that.

Howeverm I saw that page you linked to and was still having problems.  I think I just have problems visualizing test classesfor page controllers.  Any chance I get get your help, but with a simpler (I think) example to get me over the hump of testing the controllers for pages.  Here is the scenario.  I have a different Visual Force page that I open up with a single parameter in the URL.  The parameter, 'groupid', is the Id of a custom object called Product_Group__c.  So I believe what I need to test is opening the page 'CP_DownloadGroup' with parameter passed to it  - like this 'apex/CP_DownloadGroup?groupid=<id value>'.    I have the test below, which gets me 25% coverage - basically everything but the query that uses the ID to pull the needed data.  What am I missing? Can you help?

@isTest
public class CP_PageTests {

static testmethod void testCPDownloadGroup() {

    ApexPages.StandardSetController setCon;
        Product_Group__c pg = new Product_Group__c(Name='TestGroup',
            Active__c = true,
            Release_Images__c='www.cnet.com',
            Updates_and_Fixes__c='www.google.com');
        insert pg;

     PageReference pageRef = new PageReference('/apex/CP_DownloadGroup?groupid=' + pg.Id);

System.assertNotEquals(null, pg.Id);
     Test.setCurrentPage(pageRef);
     CPDownloadGroup controller = new CPDownloadGroup();
   
    }

}

pconpcon
You can add parameters to your page reference by doing:

PageReference pageRef = new Page.CP_DownloadGroup;
Test.setCurrentPage(pageRef);

ApexPages.currentPage().getParameters().put('groupid', pg.Id);

That should let your controller access them via get parameter
Glenn at MvistaGlenn at Mvista
pcon, thanks again (just getting back to this).  I am able to get the ID in there, and the log shows it:

16:50:01:063 VARIABLE_ASSIGNMENT [13]|pageRef|"/apex/CP_DownloadGroup?groupid=a1QR0000002eReYMAU"|0x2a6d32ff

However, the class still only shows 25% coverage and nothing is getting test coverage that needs it.

User-added image

Any more help you can provide would be appreciated.  Here is the rest of the code:

Test Class
static testmethod void testCPDownloadGroup() {

        Product_Group__c pg = new Product_Group__c(Name='TestGroup', 
        				Active__c = true, 
        				Release_Images__c='www.cnet.com', 
        				Updates_and_Fixes__c='www.google.com');
        insert pg;

		PageReference pageRef = new PageReference('/apex/CP_DownloadGroup?groupid=' + pg.Id);

    	CPDownloadGroup controller = new CPDownloadGroup();
    	system.Test.setCurrentPage(pageRef);
    	ApexPages.currentPage().getParameters().put('groupid', pg.Id);
    }
CPDownloadGroup.cls
public class CPDownloadGroup {

    Product_Group__c pg;

    public Product_Group__c getpg() {
        	pg = [select Id, 
        				Name, 
        				Active__c, 
        				Release_Images__c, 
        				Updates_and_Fixes__c 
        			from Product_Group__c 
                 where Id = :ApexPages.currentPage().getParameters().get('groupid') and Active__c = true]; 
        return pg;
        }
}
and here is the page itself
<apex:page controller="CPDownloadGroup" sidebar="true" showHeader="true">
<apex:variable var="g" value="{!pg}" />
    <apex:iframe src="{!g.Release_Images__c}?check_login={!$User.Email}" scrolling="true" />
</apex:page>



pconpcon
The problem is that your page has nothing to do with your tests.  Unfortunately all of the controller testing has to be done manually.  So for this your test should look like

static testmethod void testCPDownloadGroup() {
     Product_Group__c pg = new Product_Group__c(
          Name='TestGroup', 
          Active__c = true, 
          Release_Images__c = 'www.cnet.com',
          Updates_and_Fixes__c = 'www.google.com'
     );
     insert pg;

     PageReference pageRef = new PageReference('/apex/CP_DownloadGroup?groupid=' + pg.Id          );

     CPDownloadGroup controller = new CPDownloadGroup();
     System.Test.setCurrentPage(pageRef);
     ApexPages.currentPage().getParameters().put('groupid', pg.Id);

     Test.startTest();

     Product_Group__c result = controller.getpg();

     Test.stopTest();

     System.assertEquals(pg.Id, result.Id);
}

You'll probably want to think about doing some additional error checking in your getpg method in case the groupid parameter is not set or if Product_Group__c does not exist.
This was selected as the best answer
Glenn at MvistaGlenn at Mvista
That makes sense (and provides coverage).  I truly appreciate the help.

Glenn