Subclass and Override: A Legacy Code Technique

Let’s move on to singletons we don’t own. To add a layer of indirection around the singleton, we’ll extend the calling code. An important dependency-breaking technique from Working Effectively with Legacy Code [Fea04] is Subclass and Override Method.

The idea is to create a subclass of production code that lives only in test code, or a test-specific subclass.[19] It gives us a way to override methods that are problematic for testing.

Let’s apply this to OverrideViewController, which starts with this initial method:

 override​ ​func​ ​viewDidAppear​(_ animated: ​Bool​) {
 super​.​viewDidAppear​(animated)
 Analytics​.shared.​ ...

Get iOS Unit Testing by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.