0Pricing
Swift Academy · Lesson

Mocking Dependencies in Tests

Swap real implementations for test doubles.

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))

All lessons in this course

  1. Why Dependency Injection
  2. Constructor Injection
  3. Protocol-Based Abstractions
  4. Mocking Dependencies in Tests
← Back to Swift Academy