Newer Version Available
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 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).
-
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.