3

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;
    }
  • Please add a snippet of the VF page – cropredy May 8 '16 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. – Ilya Lepesh May 8 '16 at 5:02
2

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!

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.