0
0
Swiftprogramming~3 mins

Why Test doubles (mocks, stubs) in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could test your app perfectly without depending on real-world signals or slow services?

The Scenario

Imagine you are testing a car's navigation app that needs live GPS data and internet maps. Without test doubles, you must rely on real GPS signals and internet connections every time you test.

The Problem

This manual way is slow and unreliable. If GPS is weak or internet is down, your tests fail even if your code is fine. Also, you can't easily test rare cases like wrong locations or no signal.

The Solution

Test doubles like mocks and stubs act as pretend parts. They give fixed GPS data or fake internet responses instantly. This makes tests fast, reliable, and lets you check how your app handles all situations.

Before vs After
Before
let location = realGPS.getLocation()
let map = realInternet.fetchMap(location)
After
let location = stubGPS.getFixedLocation()
let map = mockInternet.fetchFakeMap(location)
What It Enables

Test doubles let you test your code anytime, anywhere, and for every possible case without waiting or failing due to outside problems.

Real Life Example

When building a weather app, you can use stubs to simulate sunny or rainy weather data, so you see how your app looks without waiting for actual weather changes.

Key Takeaways

Manual testing with real parts is slow and unreliable.

Test doubles replace real parts with pretend ones for fast, stable tests.

This helps test all scenarios easily and confidently.