Unit Tests

Unit tests are mandatory for all Apex code, including Visualforce controllers but not the pages themselves. Your application code must have at least 75% test coverage before it can be deployed to a production environment.

The mechanics of writing unit tests for controllers is similar to that of triggers, with some additional system methods for test setup. But the strategy for testing controllers is unique, because controller code normally relies on the Web browser to drive it.

Listing 6.19 provides an example of the test setup code. It starts by creating an instance of the controller class and getting a reference to the Visualforce page to test. This is a PageReference instance, created by passing the page name as an argument. The Test.setCurrentPage method sets the context of the test method to the page you want to test.

Listing 6.19 Sample Controller Test Method


static testMethod void sampleTestMethod() {
  MyPageController controller = new MyPageController();
  PageReference page = new PageReference('MyPage'),
  Test.setCurrentPage(page);
}


The body of your tests can employ one or more of the following test strategies to exercise code in the controller:

Image Directly invoke controller methods and getters/setters.

Image Add a test harness to constructor code to read URL arguments to establish controller state or perform actions.

Image Verify data in the database using SOQL and SOSL queries.

Image Use System.runAs blocks to simulate different users, such as System.runAs(user) { block; }.


Caution

Even 100% test coverage on the controller class does not guarantee a bug-free user interface. Testing Visualforce pages is like testing any Web application. Test it manually with your Web browser or with an automated Web testing tool.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.238.171