Extract a Protocol to Support Test Doubles
The userDefaults property currently has an implicit type of UserDefaults. If we kept that type, then any replacement would have to be UserDefaults or a subclass. Subclassing is useful for allowing existing behavior to flow through, capturing extra information. (See How to Spy on the Animated Flag.) But subclassing isn’t useful when you want to stop some existing behavior. It also isn’t useful when the type is a final class or a struct, or the type prevents you from creating your own instance of it.
What we need is a way to substitute an arbitrary type that honors a contract. In Swift, we can do this using protocols. Protocols give us a way to replace a concrete type with a test double.
What’s ... |
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.