Test Doubles: Mock, Stub, Spy, Fake

The interviewer asks

“What's the difference between mock, stub, spy, and fake?”

How to answer

They're all test doubles, and they differ by what they're for. A stub feeds canned answers into the code under test; a spy records the calls it receives so the test can assert on them afterwards; a mock is a spy that also carries the expectations and verifies them; a fake is a real but simplified implementation, like an in-memory repository. There's also the dummy, a value passed only to satisfy a signature. I pick the weakest double that answers the question the test is asking.

Key points

  • Stub: controls indirect input (what the dependency returns or throws)
  • Spy: captures indirect output (which calls were made, with which arguments)
  • Mock: spy + built-in expectations (verify()); assertions live in the double
  • In Swift 6 the protocol is usually Sendable: stubs are structs, spies/fakes with state are actors, @MainActor classes or Mutex-backed

If they dig deeper

  • Which one most often? Stubs and fakes; they keep tests about outcomes. Spies when the side effect is the behavior (analytics sent). Terms come from Meszaros' xUnit Test Patterns; many teams say "mock" for all of them.
  • Why a Mutex spy rather than an actor? Callers can read spy.savedUsers synchronously, with no await, and it's still Sendable.
  • Fakes need their own tests: if the in-memory repository diverges from the real one, tests lie; run one shared contract test suite against both.

Common pitfalls

  • Calling everything a mock, then over-verifying calls everywhere
  • Fakes that grow real business logic and drift from production
  • Spies with unprotected var arrays marked @unchecked Sendable

How to use it

swift
import Synchronization

protocol UserRepository: Sendable {
    func user(id: Int) async throws -> User
    func save(_ user: User) async throws
}

// Stub: canned answers in, nothing recorded
struct StubRepository: UserRepository {
    let user: User
    func user(id: Int) async throws -> User { user }
    func save(_ user: User) async throws {}
}

// Spy: records calls; Mutex makes it Sendable and readable without await
final class SpyRepository: UserRepository {
    private let saved = Mutex<[User]>([])
    var savedUsers: [User] { saved.withLock { $0 } }
    func user(id: Int) async throws -> User { User(id: id, name: "Spy") }
    func save(_ user: User) async throws { saved.withLock { $0.append(user) } }
}

// Fake: real (simplified) behavior, in memory
actor InMemoryRepository: UserRepository {
    private var storage: [Int: User] = [:]
    func user(id: Int) async throws -> User {
        guard let user = storage[id] else { throw RepositoryError.notFound }
        return user
    }
    func save(_ user: User) async throws { storage[user.id] = user }
}
swift
import Testing

@MainActor
@Suite struct RenameTests {
    @Test func renameSavesUpdatedUser() async throws {
        let spy = SpyRepository()
        try await ProfileViewModel(repository: spy).rename(to: "Grace")
        #expect(spy.savedUsers.map(\.name) == ["Grace"])   // spy: assert the call
    }

    @Test func renameIsVisibleOnReload() async throws {
        let fake = InMemoryRepository()
        let viewModel = ProfileViewModel(repository: fake)
        try await viewModel.rename(to: "Grace")
        #expect(try await fake.user(id: viewModel.userID).name == "Grace")   // fake: assert state
    }
}

Best practices

  • Choose the weakest double that answers the test's question
  • Prefer stubs and fakes (outcomes) over mocks (interactions)
  • Protect recorded state with actor, @MainActor or Mutex

Related concepts

  • mocking, fake vs mock, test doubles best practices, contract testing, dependency injection, Mutex, actors