When you realize you can write unit tests against view controllers, it’s exciting. At first, you may think this will unlock your codebase to automated testing: “I can test anything!”
Unfortunately, as you try to make progress, you’ll experience setbacks and frustrations. Sure, you can write a test that accesses a particular view controller. But as soon as you try to have a test call some method, you find the code inside the view controller is fighting you.
This is true of any types, not only view controllers. Code written without tests often has implicit hardwired dependencies. These dependencies can complicate testing. It so happens that view controllers are especially susceptible to such problems. It’s easy to lump functionality (and the dependencies needed to perform it) into a view controller.
When testing is difficult, this reveals flaws in the architectural design of the code. By making changes to enable testing, you’ll be shaping the code into cleaner design. Design decisions that were once hidden and implicit will become visible and explicit.
In this chapter, we’ll learn how to identify difficult dependencies. Having identified them, we’ll explore some techniques for isolating these dependencies. This will give you ways to write unit tests against previously untestable code.