0
0
iOS Swiftmobile~5 mins

Mock objects and protocols in iOS Swift

Choose your learning style9 modes available
Introduction

Mock objects help us test parts of our app by pretending to be real parts. Protocols define rules that these parts must follow.

When you want to test a screen without using real data from the internet.
When you want to check if a button calls the right function.
When you want to replace a slow or complex part with a simple fake one during testing.
Syntax
iOS Swift
protocol SomeProtocol {
    func doSomething()
}

class MockObject: SomeProtocol {
    func doSomething() {
        // fake implementation for testing
    }
}
Protocols define what methods or properties a class or struct must have.
Mock objects are classes or structs that follow a protocol but have simple code for testing.
Examples
This mock fetcher returns fixed data instead of real data.
iOS Swift
protocol DataFetcher {
    func fetchData() -> String
}

class MockFetcher: DataFetcher {
    func fetchData() -> String {
        return "Mock data"
    }
}
This mock logger saves messages in a list so tests can check them later.
iOS Swift
protocol Logger {
    func log(message: String)
}

class MockLogger: Logger {
    var messages = [String]()
    func log(message: String) {
        messages.append(message)
    }
}
Sample App

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.

iOS Swift
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)
OutputSuccess
Important Notes

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.

Summary

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.