You’ve probably seen a bloated viewDidLoad()
method that’s doing eight different things such as:
- Fetch data over the network
- Display the data in the table view
- Update the contents in Core Data
- Upload photos from camera or albums
- Style table view cells with complex subviews
- Execute different branches depending on whether the user is logged in or not
- Check IAP to see which products should be made available
- Fire off some background tasks
It’s impossible to write unit tests for a bloated viewDidLoad()
method like this. Even if you manage to do so by plowing through the frustrations, the resulting tests won’t be of much value. The reason is simple. The behaviors are complex and inconsistent. There are too many use cases lumped into one single method. You won’t trust your tests to give you the confidence you need to ensure you aren’t breaking anything when making changes.
If you ever wonder about these two questions:
- How to refactor the
viewDidLoad()
method to slim it down? - How do you write unit tests for it?
Then you should read on to learn the 1-2-3 step process to improve your code.