What if you could test your app perfectly without depending on real-world signals or slow services?
Why Test doubles (mocks, stubs) in Swift? - Purpose & Use Cases
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.
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.
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.
let location = realGPS.getLocation() let map = realInternet.fetchMap(location)
let location = stubGPS.getFixedLocation() let map = mockInternet.fetchFakeMap(location)
Test doubles let you test your code anytime, anywhere, and for every possible case without waiting or failing due to outside problems.
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.
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.
Practice
mock in Swift testing?Solution
Step 1: Understand what a mock does
A mock is a test double that records how it was used, such as which methods were called and with what arguments.Step 2: Compare with other test doubles
Unlike stubs, mocks focus on interaction verification, not just providing fixed answers.Final Answer:
To record how a function was called during a test -> Option AQuick Check:
Mock = Records calls [OK]
- Confusing mocks with stubs
- Thinking mocks speed up production
- Believing mocks replace the whole app
Solution
Step 1: Check method signature and return type
The method must return an Int, so the signature should befunc getNumber() -> Int.Step 2: Verify the return statement
The method should return the integer 42, soreturn 42is correct.Final Answer:
func getNumber() -> Int { return 42 } -> Option AQuick Check:
Stub returns fixed value [OK]
- Missing return type in function signature
- Returning wrong data type
- Using print instead of return
class ServiceMock {
var fetchCalled = false
func fetchData() {
fetchCalled = true
}
}
let mock = ServiceMock()
mock.fetchData()
print(mock.fetchCalled)
What will be printed?Solution
Step 1: Understand the mock class behavior
The class has a boolean propertyfetchCalledinitially false. The methodfetchData()sets it to true.Step 2: Trace the code execution
After creatingmock, callingmock.fetchData()setsfetchCalledto true. Printing it outputs true.Final Answer:
true -> Option BQuick Check:
Mock records call = true [OK]
- Assuming fetchCalled stays false
- Expecting nil instead of Bool
- Thinking code won't compile
class DataStub {
func getData() -> String {
print("Fixed data")
}
}
What is the error and how to fix it?Solution
Step 1: Identify the method signature and body
The method declares it returns a String but only callsprintwithout returning anything.Step 2: Fix the missing return
Replaceprint("Fixed data")withreturn "Fixed data"to satisfy the return type.Final Answer:
Missing return statement; addreturn "Fixed data"-> Option DQuick Check:
Stub must return value, not print [OK]
- Confusing print with return
- Changing method name unnecessarily
- Changing return type incorrectly
Downloader that calls a network service. To avoid real network calls, you create a mock service that records if download() was called and a stub that returns fixed data. Which approach correctly combines mocks and stubs for this test?Solution
Step 1: Understand roles of mocks and stubs
Mocks record interactions like method calls; stubs provide fixed return data.Step 2: Apply correct combination
Use a mock to check ifdownload()was called, and a stub to supply fixed data forfetchData()to avoid real network calls.Final Answer:
Use a mock to recorddownload()calls and a stub to return fixed data whenfetchData()is called -> Option CQuick Check:
Mock records calls + Stub returns data [OK]
- Using only one test double type
- Relying on real network in tests
- Confusing mock and stub roles
Ready to prove it?
Pass the test and this pattern moves unknown
