External Dependencies and Their Challenges
Understand the challenges external dependencies bring to unit testing, especially when tightly coupled. Learn how to use dependency injection and mocks to create loosely coupled classes that enable reliable and controlled unit tests. This lesson helps you manage dependencies effectively to write maintainable and testable code.
Introduction
A dependency is a class or object that another class or object relies on. In object-oriented languages, the application code consists of classes where some classes rely on other classes. In this context, relying means that one class is referenced in the other class code. It could be included in any of its method parameters, its method return types, or even in any of its method implementations. This concept is shown below where Class A depends on Class B. In this context, Class B is a dependency.
Dependency example
The example below further demonstrates the simple concept of dependency. Suppose we have a BankAccount class that contains an Amount field. The Withdraw and Deposit methods allow for withdrawing and depositing funds to and from the bank account. This class is designed to enable withdrawals on weekdays only. To achieve this business rule, the DayChecker class is used, which returns whether the transaction date is on a weekday.
The dependency DayChecker class is shown below:
In the example shown above, the ...