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 asharedinstance - Assert outcomes first; assert interactions only when the call itself is the requirement
If they dig deeper
- Why not
@unchecked Sendableon the mock? It silences the compiler without making the recorded array safe; anactororMutexgives the same convenience with real guarantees. - Actor vs
@MainActormock: an actor means readingawait spy.requestedIDs; if the view model is@MainActor, a@MainActor final classmock 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
Sendableprotocols at boundaries you own - Inject through
init(any Protocolor a generic parameter) - Prefer stubs and outcome assertions; add spies only for interactions that matter
- Make recorded state safe with
actor,@MainActororMutex, 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