Introduction
Mock objects help us test parts of our app by pretending to be real parts. Protocols define rules that these parts must follow.
Mock objects help us test parts of our app by pretending to be real parts. Protocols define rules that these parts must follow.
protocol SomeProtocol {
func doSomething()
}
class MockObject: SomeProtocol {
func doSomething() {
// fake implementation for testing
}
}protocol DataFetcher {
func fetchData() -> String
}
class MockFetcher: DataFetcher {
func fetchData() -> String {
return "Mock data"
}
}protocol Logger {
func log(message: String)
}
class MockLogger: Logger {
var messages = [String]()
func log(message: String) {
messages.append(message)
}
}This program uses a mock greeter to print a greeting message. It shows how mocks follow protocols and can be used instead of real objects.
import Foundation protocol Greeter { func greet() -> String } class MockGreeter: Greeter { func greet() -> String { return "Hello from mock!" } } func welcomeUser(greeter: Greeter) { print(greeter.greet()) } let mock = MockGreeter() welcomeUser(greeter: mock)
Mocks help isolate parts of your app so you can test them easily.
Protocols make your code flexible and testable by defining clear rules.
Use mocks to avoid slow or unreliable parts during testing.
Mock objects pretend to be real parts for testing.
Protocols define what methods or properties a type must have.
Mocks follow protocols and provide simple, test-friendly behavior.
protocol.protocol keyword correctly; others use class, struct, or interface which are incorrect for protocols.mock.fetchData()?
protocol DataFetcher {
func fetchData() -> String
}
class MockFetcher: DataFetcher {
func fetchData() -> String {
return "Mock Data"
}
}
let mock = MockFetcher()
print(mock.fetchData())fetchData() returning a String. The mock class implements it returning "Mock Data".mock.fetchData() returns "Mock Data", so that is printed.protocol Service {
func execute() -> Bool
}
class MockService: Service {
func execute() {
print("Executed")
}
}execute() to return a Bool, but the mock method returns Void.protocol NetworkService {
func fetchData(completion: (String) -> Void)
}
class MockNetworkService: NetworkService {
func fetchData(completion: (String) -> Void) {
completion("Test Data")
}
}
// In test:
let mockService = MockNetworkService()
let viewController = MyViewController(service: mockService)
viewController.loadData()
What is the benefit of this setup?Pass the test and this pattern moves unknown