What is Embedded Linux?

The demand for faster, efficient, and high-performing computers is increasing, the dimensions of the form factors that carry them forward decrease. These days, the IT industry and engineers are…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Extract a Protocol to Support Test Doubles

iOS Unit Testing by Example — by Jon Reid (120 / 223)

👈 Isolate UserDefaults with Depen dency Injection | TOC | Make a Fake Object 👉

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.

images/aside-icons/info.png

What’s a test double? It’s like a stunt double in filmmaking. We temporarily replace the real actor with someone that looks like that actor. Or in our case, something that looks like the original type as far as the calling code is concerned.

Start by defining a new protocol in production code. For lack of a better name, let’s call it UserDefaultsProtocol. It’ll be empty to start with:

Now add an explicit type to the userDefaults property, specifying the protocol.

Xcode will show a Swift error:

Since Swift allows us to extend existing types, we can declare an extension saying that UserDefaults does conform to our new protocol:

Add a comment

Related posts:

How Networking Helped Me Decide On A Career Path

I have met a lot of interesting people from different technical backgrounds that have helped me learn about the industry I am getting into. Asking questions and bettering my understanding helped me a

Static vs. Dynamic Typing

This book is for everyone who needs to test the web. As a tester, you'll automate your tests. As a developer, you'll build more robust solutions. And as a team, you'll gain a vocabulary and a means to coordinate how to write and organize automated tests for the web. Follow the testing pyramid and level up your skills in user int

Use Reiki Principles to Lead an Energetic Life

People are aware of the rising physical and mental ailments in everyday life. Almost everyone feels bogged down by one form of stress or another. As a result, people are looking for different…