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
- XCTestCase Setup, Teardown and Test Methods
- XCTAssert Family and Throwing Assertions
- Protocol-Based Mocking and Dependency Injection
- Async Tests and Performance Measurement