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.
-
Create a custom controller named
NewLeadController. -
Create a page named
NewLead. -
Create a page named
Success. -
Create a page named
Failure. -
Create a test class named
NewLeadTeststhat contains the test methodtestAddNewLead. The test checks both failure and success conditions. To set the currentPageReferencefor the controller, use the methodTest.setCurrentPage(PageReference page). -
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.
See Also