Dependency Injection, Mocking, and Unit Testing
At this stage, you're probably wondering just how is it technically possible, using code, to substitute or inject (to use the correct term) different compiled code during a test execution. To illustrate the various options for Dependency Injection let's start with a simple code example. We will explore how unit testing can be applied to Apex Enterprise patterns later in this chapter.
The following diagram shows the Unified Modeling Language (UML) for a Car
class model, which has been designed with SOC in mind. Responsibilities such as engine, dashboard, and the digital readout display have been separated. This is a pure Apex code example to illustrate how dependencies between classes can be managed with Dependency Injection (DI):
The following code is for the Car
class. It has a dependency on methods from the Dashboard
and Engine
classes. The caller must set up and provide instances of these classes for the methods to function correctly...