-
Book Overview & Buying
-
Table Of Contents
Visualforce Development Cookbook - Second Edition
By :
Controller extensions provide additional functionality for standard or custom controllers. The contract for a controller extension is that it provides a constructor that takes a single argument of the standard or custom controller that it is extending. Testing a controller extension introduces an additional requirement that an instance of the standard or custom controller, with appropriate internal state, is constructed before the controller extension.
In this recipe, we will create a controller extension to retrieve the contacts associated with an account managed by a standard controller and unit test the extension.
As the test class makes reference to the controller extension, this must be created first:
AccountContactsExt.cls Apex class from the code download into the Apex Class area.AccountContactsExtTest.cls Apex class from the code download into the Apex Class area.The tests successfully execute, as shown in the following screenshot:

Open the Developer Console by clicking on your name at the top right of the screen and selecting Developer Console from the resulting drop-down menu.
Select the Tests tab and you will see the test coverage information on the right-hand side, showing 100% code coverage for the AccountContactsExt class:

The test class contains one unit test method. As unit tests do not have access to the organization data, the first task for the test is to set up the account and contact information:
Account acc=new Account(Name='Unit Test');
insert acc;
List<Contact> contacts=new List<Contact>();
contacts.add(new Contact(FirstName='Unit',
LastName='Test', Email='[email protected]',
AccountId=acc.id));
contacts.add(new Contact(FirstName='Unit',
LastName='Test 2', Email='[email protected]',
AccountId=acc.id));
insert contacts;
Next, the instance of the standard controller is instantiated:
ApexPages.StandardController std= new ApexPages.StandardController(acc);
Note that the StandardController requires the record that it is managing as a parameter to the constructor. As this is the record that will be made available to the controller extension, it must have the fields populated that the extension relies upon. In this case, the only field used by the extension is the ID of the account, and this is automatically populated when the account is inserted.
In this recipe, the records to be tested are created in the test classes. In the real world, this is likely to lead to a lot of repetition and a maintenance overhead. In that case, a utility class to handle the setup of test data would be a more robust solution.
Finally, the controller extension is instantiated, taking the standard controller as a constructor parameter, and the test verifies that the extension has successfully retrieved the associated contacts:
AccountContactsExt controller=new AccountContactsExt(std); System.assertEquals(2, controller.contacts.size());