0Pricing
Swift Academy · Lesson

Protocol-Based Mocking and Dependency Injection

Injecting test doubles via protocols without third-party mocking frameworks.

Why Protocol-Based Mocking?

Using protocols as seams enables swapping real implementations with test doubles without modifying production code.

protocol NetworkService {
  func fetch(url: URL) async throws -> Data
}
class RealNetworkService: NetworkService { /* URLSession */ }
class MockNetworkService: NetworkService { /* returns fixtures */ }

Defining the Protocol

Extract a protocol from your dependency, containing only the methods your class needs.

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

All lessons in this course

  1. XCTestCase Setup, Teardown and Test Methods
  2. XCTAssert Family and Throwing Assertions
  3. Protocol-Based Mocking and Dependency Injection
  4. Async Tests and Performance Measurement
← Back to Swift Academy