Mocking Dependencies in Tests
Swap real implementations for test doubles.
Mocking Dependencies in Tests is a free Swift Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Mocking Dependencies in Tests
A mock is a fake implementation of a dependency used in tests. Because we inject protocols, we can supply a mock instead of the real collaborator.
A Protocol to Mock
Start from a protocol describing the dependency. The real type and the mock both conform to it.
protocol UserStore {
func name(for id: Int) -> String
}
struct RealStore: UserStore {
func name(for id: Int) -> String { "User-\(id)" }
}
print(RealStore().name(for: 5))Writing a Mock
A mock conforms to the protocol but returns canned values, avoiding real network or disk access.
protocol UserStore { func name(for id: Int) -> String }
struct MockStore: UserStore {
func name(for id: Int) -> String { "Mock" }
}
print(MockStore().name(for: 99))Injecting the Mock
Pass the mock to the system under test through its initializer. The code under test cannot tell the difference.
protocol UserStore { func name(for id: Int) -> String }
struct MockStore: UserStore { func name(for id: Int) -> String { "Mock" } }
struct Profile {
let store: UserStore
func title(_ id: Int) -> String { "Hello, " + store.name(for: id) }
}
print(Profile(store: MockStore()).title(1))Recording Calls
A mock can record how it was used, so a test can assert the dependency was called correctly.
protocol Analytics { func track(_ e: String) }
class SpyAnalytics: Analytics {
var events: [String] = []
func track(_ e: String) { events.append(e) }
}
let spy = SpyAnalytics()
spy.track("open")
spy.track("buy")
print(spy.events)Asserting Behavior
After exercising the code, check the recorded data. Here we verify the right event fired.
protocol Analytics { func track(_ e: String) }
class Spy: Analytics { var last = ""; func track(_ e: String) { last = e } }
struct Checkout { let analytics: Analytics; func pay() { analytics.track("paid") } }
let spy = Spy()
Checkout(analytics: spy).pay()
print(spy.last == "paid")Stubbing Return Values
A stub returns preset values so you can test how your code reacts to specific inputs.
protocol Clock { func hour() -> Int }
struct StubClock: Clock { let value: Int; func hour() -> Int { value } }
struct Greeter { let clock: Clock; func greet() -> String { clock.hour() < 12 ? "AM" : "PM" } }
print(Greeter(clock: StubClock(value: 9)).greet())
print(Greeter(clock: StubClock(value: 18)).greet())Simulating Failure
Mocks can simulate error conditions that are hard to trigger with real dependencies, improving test coverage.
protocol Loader { func load() -> Int? }
struct FailingLoader: Loader { func load() -> Int? { nil } }
struct VM { let loader: Loader; func status() -> String { loader.load() == nil ? "error" : "ok" } }
print(VM(loader: FailingLoader()).status())Deterministic Tests
Because mocks return fixed values, tests are fast and deterministic, with no flakiness from real services.
protocol Random { func next() -> Int }
struct FixedRandom: Random { func next() -> Int { 42 } }
struct Game { let rng: Random; func roll() -> Int { rng.next() } }
print(Game(rng: FixedRandom()).roll())No Test Framework Here
In a real project these checks live in XCTest assertions. The injection pattern is identical; only the assertion syntax differs.
protocol Calc { func add(_ a: Int, _ b: Int) -> Int }
struct RealCalc: Calc { func add(_ a: Int, _ b: Int) -> Int { a + b } }
struct MockCalc: Calc { func add(_ a: Int, _ b: Int) -> Int { 0 } }
print(RealCalc().add(2, 2))
print(MockCalc().add(2, 2))The Full Loop
Define protocol, write real and mock conformers, inject the mock, exercise the code, and assert. DI makes every step possible.
protocol Repo { func count() -> Int }
struct MockRepo: Repo { func count() -> Int { 3 } }
struct Stats { let repo: Repo; func total() -> Int { repo.count() * 2 } }
print(Stats(repo: MockRepo()).total())Quick Check
What makes mocking a dependency possible in this approach?
Recap
A mock conforms to the injected protocol and returns canned values, records calls, or simulates failures. Injecting it produces fast, deterministic tests. The loop is: define protocol, write real and mock conformers, inject, exercise, assert. That completes the DI course.
Frequently asked questions
Is the “Mocking Dependencies in Tests” lesson free?
Yes — the full text of “Mocking Dependencies in Tests” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
What will I learn in “Mocking Dependencies in Tests”?
Swap real implementations for test doubles. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Mocking Dependencies in Tests” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Why Dependency Injection
- Constructor Injection
- Protocol-Based Abstractions
- Mocking Dependencies in Tests