Newer Version Available

This content describes an older version of this product. View Latest

Test a Custom Controller

To ensure error-free code, create and execute Apex unit tests for every custom controller and controller extension that you write. Unit tests are class methods that verify whether a particular piece of code works properly. Unit test methods take no arguments, commit no data to the database, and are flagged with the @isTest annotation in the method definition.

The example NewLead page creates a lead from the form data that the user provides. If the user completes all the fields with valid values, the new lead is created, and the user is directed to the Success page. Otherwise, a new lead isn’t created, and the user is directed to the Failure page.

  1. Create a custom controller named NewLeadController.
  2. Create a page named NewLead.
  3. Create a page named Success.
  4. Create a page named Failure.
  5. Create a test class named NewLeadTests that contains the test method testAddNewLead. The test checks both failure and success conditions. To set the current PageReference for the controller, use the method Test.setCurrentPage(PageReference page).
  6. Run the Apex test method in your chosen developer environment.
    You can run Apex test methods in the Developer Console, in Setup, in the Salesforce extensions for Visual Studio Code, or using the API. See Run Unit Test Methods in the Apex Developer Guide.

When testing, if the console shows the message Method does not exist or incorrect signature: Test.setCurrentPage(System.PageReference), check whether you created a class called Test. If so, rename the class.

Tip