Bird
Raised Fist0
Swiftprogramming~20 mins

Test doubles (mocks, stubs) in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Test Doubles Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a stubbed method call
What is the output of this Swift code using a stub to replace a method?
Swift
protocol DataService {
    func fetchData() -> String
}

class StubDataService: DataService {
    func fetchData() -> String {
        return "Stubbed Data"
    }
}

func printData(service: DataService) {
    print(service.fetchData())
}

let stub = StubDataService()
printData(service: stub)
AStubbed Data
BfetchData()
CDataService
DRuntime error
Attempts:
2 left
💡 Hint
The stub replaces the real method with a fixed return value.
❓ Predict Output
intermediate
2:00remaining
Mock method call count
What will be printed after running this Swift code that uses a mock to count method calls?
Swift
class MockLogger {
    var logCount = 0
    func log(_ message: String) {
        logCount += 1
        print("Log: \(message)")
    }
}

let mock = MockLogger()
mock.log("Start")
mock.log("Process")
print(mock.logCount)
A2
B0
CCompile error
D1
Attempts:
2 left
💡 Hint
The mock increments logCount every time log() is called.
🔧 Debug
advanced
2:00remaining
Why does this mock not record calls?
This Swift mock class is supposed to record calls to the method but fails. What is the cause?
Swift
class MockService {
    var callCount = 0
    func performAction() {
        var callCount = 0
        callCount += 1
    }
}

let mock = MockService()
mock.performAction()
mock.performAction()
print(mock.callCount)
AcallCount is a constant and cannot be changed.
BThe performAction method is never called.
CThe callCount inside performAction is a new local variable, not the class property.
Dprint statement is outside the class and cannot access callCount.
Attempts:
2 left
💡 Hint
Check variable scope inside the method.
🧠 Conceptual
advanced
2:00remaining
Purpose of a stub in testing
Which statement best describes the purpose of a stub in unit testing?
AA stub replaces the entire application logic with a fake implementation for integration testing.
BA stub provides canned responses to calls made during the test, isolating the tested code from external dependencies.
CA stub records every call made to it and verifies the order of calls.
DA stub automatically generates test data based on input parameters.
Attempts:
2 left
💡 Hint
Think about how stubs help isolate code under test.
❓ Predict Output
expert
2:00remaining
Output of a mock verifying call sequence
What is the output of this Swift code that uses a mock to verify the order of method calls?
Swift
class MockSequence {
    var calls: [String] = []
    func first() { calls.append("first") }
    func second() { calls.append("second") }
    func verify() -> Bool {
        return calls == ["first", "second"]
    }
}

let mock = MockSequence()
mock.second()
mock.first()
print(mock.verify())
ARuntime error
Btrue
CCompile error
Dfalse
Attempts:
2 left
💡 Hint
Check the order in which methods are called and recorded.

Practice

(1/5)
1. What is the main purpose of using a mock in Swift testing?
easy
A. To record how a function was called during a test
B. To provide fixed data without recording calls
C. To replace the entire app with a test version
D. To speed up the app in production

Solution

  1. Step 1: Understand what a mock does

    A mock is a test double that records how it was used, such as which methods were called and with what arguments.
  2. Step 2: Compare with other test doubles

    Unlike stubs, mocks focus on interaction verification, not just providing fixed answers.
  3. Final Answer:

    To record how a function was called during a test -> Option A
  4. Quick Check:

    Mock = Records calls [OK]
Hint: Mocks remember calls; stubs just return data [OK]
Common Mistakes:
  • Confusing mocks with stubs
  • Thinking mocks speed up production
  • Believing mocks replace the whole app
2. Which of the following is the correct way to define a stub method in Swift that always returns 42?
easy
A. func getNumber() -> Int { return 42 }
B. func getNumber() -> Int { print(42) }
C. func getNumber() { return 42 }
D. func getNumber() -> String { return "42" }

Solution

  1. Step 1: Check method signature and return type

    The method must return an Int, so the signature should be func getNumber() -> Int.
  2. Step 2: Verify the return statement

    The method should return the integer 42, so return 42 is correct.
  3. Final Answer:

    func getNumber() -> Int { return 42 } -> Option A
  4. Quick Check:

    Stub returns fixed value [OK]
Hint: Stub methods return fixed values with correct return type [OK]
Common Mistakes:
  • Missing return type in function signature
  • Returning wrong data type
  • Using print instead of return
3. Consider this Swift mock class snippet:
class ServiceMock {
    var fetchCalled = false
    func fetchData() {
        fetchCalled = true
    }
}

let mock = ServiceMock()
mock.fetchData()
print(mock.fetchCalled)
What will be printed?
medium
A. false
B. true
C. nil
D. Compilation error

Solution

  1. Step 1: Understand the mock class behavior

    The class has a boolean property fetchCalled initially false. The method fetchData() sets it to true.
  2. Step 2: Trace the code execution

    After creating mock, calling mock.fetchData() sets fetchCalled to true. Printing it outputs true.
  3. Final Answer:

    true -> Option B
  4. Quick Check:

    Mock records call = true [OK]
Hint: Mock flags change after method call [OK]
Common Mistakes:
  • Assuming fetchCalled stays false
  • Expecting nil instead of Bool
  • Thinking code won't compile
4. This Swift stub class is intended to return a fixed string but has a bug:
class DataStub {
    func getData() -> String {
        print("Fixed data")
    }
}
What is the error and how to fix it?
medium
A. print cannot be used in stubs; remove print
B. Wrong method name; rename to fetchData()
C. Return type should be Void; change signature
D. Missing return statement; add return "Fixed data"

Solution

  1. Step 1: Identify the method signature and body

    The method declares it returns a String but only calls print without returning anything.
  2. Step 2: Fix the missing return

    Replace print("Fixed data") with return "Fixed data" to satisfy the return type.
  3. Final Answer:

    Missing return statement; add return "Fixed data" -> Option D
  4. Quick Check:

    Stub must return value, not print [OK]
Hint: Return values, don't print in stubs [OK]
Common Mistakes:
  • Confusing print with return
  • Changing method name unnecessarily
  • Changing return type incorrectly
5. You want to test a Swift class Downloader that calls a network service. To avoid real network calls, you create a mock service that records if download() was called and a stub that returns fixed data. Which approach correctly combines mocks and stubs for this test?
hard
A. Use only a mock that returns fixed data without recording calls
B. Use only a stub that records calls and returns data
C. Use a mock to record download() calls and a stub to return fixed data when fetchData() is called
D. Use real network service to ensure accurate testing

Solution

  1. Step 1: Understand roles of mocks and stubs

    Mocks record interactions like method calls; stubs provide fixed return data.
  2. Step 2: Apply correct combination

    Use a mock to check if download() was called, and a stub to supply fixed data for fetchData() to avoid real network calls.
  3. Final Answer:

    Use a mock to record download() calls and a stub to return fixed data when fetchData() is called -> Option C
  4. Quick Check:

    Mock records calls + Stub returns data [OK]
Hint: Mocks track calls; stubs provide data [OK]
Common Mistakes:
  • Using only one test double type
  • Relying on real network in tests
  • Confusing mock and stub roles
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard