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:pageBlockSection title="Account Details">
                <apex:inputField value="{!Account.PublicName__c}" required="true"/>
                <apex:inputField value="{!Account.Code__c}" required="true"/>

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

public class AccountPortalController

    public PageReference save()

        PageReference pr;
            pr = m_stdCon.save();

        catch (Exception e)
            return null;

        return pr;
  • Please add a snippet of the VF page
    – cropredy
    May 8, 2016 at 3:48
  • 1
    Unit tests suppose to cover apex code. When you're doing test for controller, you verifying that interface works, exceptions, properties etc. There is no way to test page itself. It should be done by QA test. May 8, 2016 at 5:02

1 Answer 1


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!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .