5 Dependency injection
This chapter covers
- Exploring the challenges to testability.
- Improving testability by isolating dependencies.
- Dependency injection techniques for testability.
Previously, we developed a user-friendly command-line program called the HIT tool, which provides a command-line interface (CLI) for the HIT client. We learned how to parse command-line arguments and flags using the standard library's os and flag packages.
This chapter focuses on testing the HIT tool using various dependency injection techniques. We'll first explore the challenges we might face while testing CLI tools and how to make our tool testable. Next, we'll add CLI tests to verify its functionality and unit tests for its flag parser to cover edge cases. The combination of these tests will help ensure that our tool works correctly from the user's perspective while also effectively handling edge cases.
By the end of this chapter, you'll have a solid understanding of how to test CLI tools. While this chapter explains testing a command-line tool, you can apply the same techniques to any project where you want to isolate dependencies to have more testable code.
NOTE
This chapter requires basic knowledge of interfaces. Check out Section D.3 in Appendix D for an introduction to interfaces in Go.