Mocking and Stubbing

The interviewer asks

“How do you mock dependencies in tests?”

How to answer

I put each external dependency (network, database, clock, analytics) behind a small protocol, inject it through init, and in tests pass a hand-written double instead of the real thing. A stub just returns canned values; a mock or spy also records how it was called so I can assert on the interaction. In Swift 6 those protocols are usually Sendable, so a stateless stub can be a plain struct, and a mock with recorded state is an actor, a @MainActor final class, or Mutex-backed. Swift has no runtime mocking like Mockito, so doubles are written by hand or generated.

Key points

  • Protocol at the boundary; the system under test depends on any UserAPI (or a generic), never on the concrete client
  • Inject through init; never swap a global or a shared instance
  • Assert outcomes first; assert interactions only when the call itself is the requirement

If they dig deeper

  • Why not @unchecked Sendable on the mock? It silences the compiler without making the recorded array safe; an actor or Mutex gives the same convenience with real guarantees.
  • Actor vs @MainActor mock: an actor means reading await spy.requestedIDs; if the view model is @MainActor, a @MainActor final class mock lets the test read it synchronously.
  • What to mock / generate: only slow, non-deterministic or side-effecting dependencies (network, disk, time); Sourcery or macro-based packages can generate mocks once protocols are many and stable.

Common pitfalls

  • Mocking types you don't own (URLSession, UserDefaults) directly instead of wrapping them in your own protocol
  • Over-specified mocks that assert every call, so any refactor breaks the test
  • Global swap points (APIClient.shared = mock): Swift 6 rejects mutable statics, and parallel tests would race anyway

How to use it

swift
import Testing

protocol UserAPI: Sendable {
    func fetchUser(id: Int) async throws -> User
}

// Stub: canned answer, no state, so a struct is Sendable for free
struct StubUserAPI: UserAPI {
    var result: Result<User, any Error>
    func fetchUser(id: Int) async throws -> User { try result.get() }
}

// Spy/mock: records calls; an actor keeps the recorded state race-free
actor SpyUserAPI: UserAPI {
    private(set) var requestedIDs: [Int] = []
    func fetchUser(id: Int) async throws -> User {
        requestedIDs.append(id)
        return User(id: id, name: "Ada")
    }
}

@MainActor
@Suite struct ProfileViewModelTests {
    @Test func loadShowsName() async {
        let viewModel = ProfileViewModel(api: StubUserAPI(result: .success(User(id: 1, name: "Ada"))))
        await viewModel.load(id: 1)
        #expect(viewModel.name == "Ada")
    }

    @Test func loadRequestsTheSelectedUser() async {
        let api = SpyUserAPI()
        let viewModel = ProfileViewModel(api: api)
        await viewModel.load(id: 42)
        #expect(await api.requestedIDs == [42])
    }
}

Best practices

  • Define small Sendable protocols at boundaries you own
  • Inject through init (any Protocol or a generic parameter)
  • Prefer stubs and outcome assertions; add spies only for interactions that matter
  • Make recorded state safe with actor, @MainActor or Mutex, not @unchecked Sendable

Related concepts

  • test doubles (stub, spy, mock, fake), fake vs mock, test doubles best practices, dependency injection, URLProtocol, view model testing, Sendable