[SalesForce] How to test for Visualforce required fields in Apex

I have a VF page with some required fields on it. These fields are not marked as required in the data model, and my controller is not doing any validation on them either. How can I properly test this page so that when save() is called I get the page validation error? Using ApexPages.hasMessages() returns false in my unit test.

<apex:page standardController="Account" extensions="AccountPortalController">
    <apex:pageMessages />

    <apex:form >
        <apex:pageBlock title="Account Information">
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:pageBlockButtons>

            <apex:pageBlockSection title="Account Details">
                <apex:inputField value="{!Account.PublicName__c}" required="true"/>
                <apex:inputField value="{!Account.Code__c}" required="true"/>
            </apex:pageBlockSection>
        <apex:pageBlock
    </apex:form>
</apex:page>

The controller overrides save() in which some logic is performed before calling StandardController.save().

public class AccountPortalController
{
    ...

    public PageReference save()
    {
        ...

        PageReference pr;
        try
        {
            pr = m_stdCon.save();

            ...
        }
        catch (Exception e)
        {
            ApexPages.addMessages(e);
            return null;
        }

        return pr;
    }

Best Answer

Apex unit tests are good to test your controller logic. Unfortunately, there is no built in mechanism to test your UI layer in Salesforce (which is always a bit of a pain).

In addition, making the fields required just in the UI layer is a brittle approach. What would happen if somebody called your controller logic directly, supplying blank field values?

You have different approaches:

  • Make the fields required in your save() method (ie: check for String.isNotBlank()). If that condition is not met, you can throw your own exception and your controller will add the error message.
  • Even better, make those fields required in the data model

If, for any reason, neither of the above approaches are valid, then your other option is to test your page using UI test automation. Selenium is one of the most common UI testing frameworks. The issue is that Selenium tests need to be built on a different stack (for instance, Java or .Net).

Good luck!

Related Topic