Newer Version Available

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

Testing Custom Controllers and Controller Extensions

Controller extensions and custom controllers, like all Apex scripts, should be covered by unit tests. Unit tests are class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit no data to the database, and are flagged with the testMethod keyword in the method definition.

When writing unit tests for controller extension and custom controller classes, you can set query parameters that can then be used in the tests. For example, the following custom controller and markup is based on the example from Controller Methods, but has been extended to expect the following query parameter in the URL for the page: ?qp=yyyy. A test method class follows, which exercises the functionality of this page:

The controller calls two additional pages: a success page and a failure page. The text of those pages is not important for this example. They merely have to exist.

The following markup uses the controller above:

The following class tests the controller:

If you are testing your controller you may see the following error message:

Tip