0
0
Swiftprogramming~30 mins

Test doubles (mocks, stubs) in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Test doubles (mocks, stubs) in Swift
📖 Scenario: You are building a simple app that fetches user data from a server. To test your code without calling the real server, you will use test doubles called mocks and stubs.
🎯 Goal: Learn how to create and use test doubles (mocks and stubs) in Swift to test code that depends on external services.
📋 What You'll Learn
Create a protocol for user data fetching
Create a stub class that returns fixed user data
Create a mock class that records method calls
Write a test function that uses the stub and mock to verify behavior
💡 Why This Matters
🌍 Real World
Test doubles help developers test code that depends on external systems without needing the real systems available.
💼 Career
Understanding mocks and stubs is essential for writing reliable automated tests in software development jobs.
Progress0 / 4 steps
1
Create a protocol for user data fetching
Create a protocol called UserDataFetcher with a function fetchUser(id: Int) -> String that returns a String.
Swift
Need a hint?

A protocol defines a blueprint of methods. Use protocol UserDataFetcher and declare the function inside.

2
Create a stub class that returns fixed user data
Create a class called UserDataStub that conforms to UserDataFetcher. Implement fetchUser(id: Int) to always return the string "Stub User".
Swift
Need a hint?

Make a class that says it follows the protocol. Then write the function to return the fixed string.

3
Create a mock class that records method calls
Create a class called UserDataMock that conforms to UserDataFetcher. Add a variable calledWithId of type Int? to record the id passed. Implement fetchUser(id: Int) to save the id to calledWithId and return "Mock User".
Swift
Need a hint?

Make a class that saves the id it receives and returns a fixed string.

4
Write a test function that uses the stub and mock
Write a function called testUserDataFetchers(). Inside, create an instance of UserDataStub and call fetchUser(id: 1). Then create an instance of UserDataMock, call fetchUser(id: 42), and print calledWithId from the mock.
Swift
Need a hint?

Call the stub and mock, then print the mock's recorded id.