Mocking Dependencies in Tests
Swap real implementations for test doubles.
Mocking Dependencies in Tests
A mock is a fake implementation of a dependency used in tests. Because we inject protocols, we can supply a mock instead of the real collaborator.
A Protocol to Mock
Start from a protocol describing the dependency. The real type and the mock both conform to it.
protocol UserStore {
func name(for id: Int) -> String
}
struct RealStore: UserStore {
func name(for id: Int) -> String { "User-\(id)" }
}
print(RealStore().name(for: 5))All lessons in this course
- Why Dependency Injection
- Constructor Injection
- Protocol-Based Abstractions
- Mocking Dependencies in Tests