0
0
Swiftprogramming~5 mins

Test doubles (mocks, stubs) in Swift

Choose your learning style9 modes available
Introduction

Test doubles help us check parts of our code by pretending to be other parts. They make testing easier and safer.

When you want to test a function without calling a real database.
When you want to check if a function calls another function correctly.
When you want to simulate different responses from a service without using the real one.
When you want to isolate a part of your code to find bugs easily.
Syntax
Swift
protocol Service {
    func fetchData() -> String
}

class StubService: Service {
    func fetchData() -> String {
        return "Stub data"
    }
}

class MockService: Service {
    var fetchDataCalled = false
    func fetchData() -> String {
        fetchDataCalled = true
        return "Mock data"
    }
}

A stub provides fixed answers to calls.

A mock records if and how it was used.

Examples
This stub always returns the same data without doing anything else.
Swift
class StubService: Service {
    func fetchData() -> String {
        return "Fixed stub data"
    }
}
This mock remembers if fetchData() was called, so tests can check that.
Swift
class MockService: Service {
    var fetchDataCalled = false
    func fetchData() -> String {
        fetchDataCalled = true
        return "Mock data"
    }
}
Sample Program

This program shows how a stub returns fixed data and a mock tracks if its method was called.

Swift
protocol Service {
    func fetchData() -> String
}

class StubService: Service {
    func fetchData() -> String {
        return "Stub data"
    }
}

class MockService: Service {
    var fetchDataCalled = false
    func fetchData() -> String {
        fetchDataCalled = true
        return "Mock data"
    }
}

func testWithStub() {
    let service = StubService()
    let data = service.fetchData()
    print("Stub returned: \(data)")
}

func testWithMock() {
    let service = MockService()
    _ = service.fetchData()
    print("Mock fetchDataCalled: \(service.fetchDataCalled)")
}

testWithStub()
testWithMock()
OutputSuccess
Important Notes

Use stubs when you only need to provide simple data for tests.

Use mocks when you want to check if certain methods were called or how many times.

Test doubles help keep tests fast and independent from real services.

Summary

Test doubles replace real parts to make testing easier.

Stubs give fixed answers; mocks remember how they were used.

They help test code without relying on real external things.