Testing the Service layer

It is tempting to allow the testing of the Service layer to be done via tests around the calling code, such as Visualforce controller tests. However, depending solely on this type of testing leaves the Service layer logic open to other use cases that may not strictly be covered by the controller logic. For example, a custom controller using StandardController will only pass in a single record and not multiple ones. Make sure to develop specific Apex tests against the Service layer as the functionality is developed.

Mocking the Service layer

Sometimes, the data setup requirements of the Service layer are such that it makes writing Apex tests for controllers or other callers, such as Batch Apex, quite complex and thus expensive, not only in terms of server time for the test to run (due to data setup for each test method) but also in terms of developer time, while preparing a full set of test data.

While you still need to test the full stack of your code, there is an approach called mocking, which can be used in conjunction with the previously mentioned factory pattern, which will allow the test context for the given service caller to implement its own test implementation of the service that mimics (with hardcoded test responses) different behaviors that the controller is expecting from the service method. This allows the controller tests to be more varied and focused when devising tests. Again, this mocking approach has to be used in combination with full stack tests that truly execute all the code required. Chapter 12, Apex Mocks, will cover mocking the Service layer in more detail.

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

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