Bird
Raised Fist0
iOS Swiftmobile~20 mins

Mock objects and protocols in iOS Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Mock Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
1:30remaining
Why use protocols for mocking in Swift?
In Swift, why do developers often use protocols when creating mock objects for testing?
AProtocols define a blueprint that mocks can implement, allowing tests to substitute real objects easily.
BProtocols automatically generate mock objects without extra code.
CProtocols prevent any code from being tested unless mocks are used.
DProtocols are only used to improve app performance, not for mocking.
Attempts:
2 left
💡 Hint
Think about how protocols help replace real objects with test doubles.
❓ ui_behavior
intermediate
1:30remaining
Mock object behavior in a login test
Given a protocol Authenticator with a method login(username:password:), which mock implementation correctly simulates a successful login for testing a login screen UI?
iOS Swift
protocol Authenticator {
  func login(username: String, password: String) -> Bool
}

class MockAuthenticator: Authenticator {
  func login(username: String, password: String) -> Bool {
    // Which return value simulates success?
    return ???
  }
}
Areturn true
Breturn false
Creturn nil
Dthrow an error
Attempts:
2 left
💡 Hint
Success means the login method should indicate a positive result.
❓ lifecycle
advanced
2:00remaining
Mock object lifecycle in unit tests
In Swift unit tests, when using a mock object that conforms to a protocol, what is the best practice to ensure the mock's state resets between tests?
ACreate a new mock instance in the <code>setUp()</code> method before each test runs.
BReuse the same mock instance for all tests to save memory.
CCreate the mock once in <code>init()</code> and never reset it.
DUse global variables to store mock state across tests.
Attempts:
2 left
💡 Hint
Think about test isolation and avoiding shared state.
📝 Syntax
advanced
2:00remaining
Correct protocol mock syntax in Swift
Which of the following Swift code snippets correctly defines a mock class that conforms to the protocol DataFetcher with a method fetchData() -> String?
iOS Swift
protocol DataFetcher {
  func fetchData() -> String
}
A
class MockFetcher: DataFetcher {
  func fetchData() -&gt; String {
    return "mock data"
  }
}
B
class MockFetcher: DataFetcher {
  func fetchData() {
    return "mock data"
  }
}
C
class MockFetcher: DataFetcher {
  func fetchData() -&gt; Int {
    return 123
  }
}
D
class MockFetcher {
  func fetchData() -&gt; String {
    return "mock data"
  }
}
Attempts:
2 left
💡 Hint
Check method signature matches protocol exactly.
🔧 Debug
expert
2:30remaining
Why does this mock cause a runtime error?
Consider this mock class in Swift: class MockService: ServiceProtocol { func fetchData() -> String { fatalError("Not implemented") } } Why will using this mock in tests cause a runtime crash?
ABecause calling fetchData() triggers fatalError, which stops the program immediately.
BBecause the mock does not conform to ServiceProtocol correctly.
CBecause fetchData() returns the wrong data type.
DBecause fatalError is only allowed in production code, not tests.
Attempts:
2 left
💡 Hint
What does fatalError() do when called?

Practice

(1/5)
1. What is the main purpose of a mock object in Swift testing?
easy
A. To improve app performance in production
B. To simulate real objects for testing without using actual implementations
C. To create user interface elements dynamically
D. To store user data securely

Solution

  1. Step 1: Understand the role of mock objects

    Mock objects are used to imitate real objects during testing to isolate code behavior.
  2. Step 2: Identify the purpose in testing context

    They help test code without relying on real implementations that may be complex or unavailable.
  3. Final Answer:

    To simulate real objects for testing without using actual implementations -> Option B
  4. Quick Check:

    Mock objects = simulate real objects [OK]
Hint: Mocks imitate real parts only for testing [OK]
Common Mistakes:
  • Confusing mocks with production code
  • Thinking mocks improve app speed
  • Using mocks for UI creation
2. Which of the following is the correct way to declare a protocol in Swift?
easy
A. interface MyProtocol { func doSomething() }
B. class MyProtocol { func doSomething() }
C. protocol MyProtocol { func doSomething() }
D. struct MyProtocol { func doSomething() }

Solution

  1. Step 1: Recall Swift syntax for protocols

    Protocols in Swift are declared using the keyword protocol.
  2. Step 2: Compare options

    protocol MyProtocol { func doSomething() } uses protocol keyword correctly; others use class, struct, or interface which are incorrect for protocols.
  3. Final Answer:

    protocol MyProtocol { func doSomething() } -> Option C
  4. Quick Check:

    Swift protocol declaration = protocol keyword [OK]
Hint: Protocols start with the keyword 'protocol' [OK]
Common Mistakes:
  • Using class or struct instead of protocol
  • Using 'interface' which is not Swift syntax
  • Missing the protocol keyword
3. Given the protocol and mock class below, what will be printed when calling mock.fetchData()?
protocol DataFetcher {
  func fetchData() -> String
}

class MockFetcher: DataFetcher {
  func fetchData() -> String {
    return "Mock Data"
  }
}

let mock = MockFetcher()
print(mock.fetchData())
medium
A. "Real Data"
B. Runtime crash
C. Compilation error
D. "Mock Data"

Solution

  1. Step 1: Analyze the protocol and mock class

    The protocol requires a method fetchData() returning a String. The mock class implements it returning "Mock Data".
  2. Step 2: Check the print statement output

    Calling mock.fetchData() returns "Mock Data", so that is printed.
  3. Final Answer:

    "Mock Data" -> Option D
  4. Quick Check:

    Mock method returns "Mock Data" [OK]
Hint: Mock returns its own defined value, not real data [OK]
Common Mistakes:
  • Assuming it returns 'Real Data'
  • Expecting a compile error due to protocol
  • Thinking it crashes at runtime
4. What is wrong with the following mock class implementation?
protocol Service {
  func execute() -> Bool
}

class MockService: Service {
  func execute() {
    print("Executed")
  }
}
medium
A. The mock class does not implement the protocol method signature correctly
B. The mock class should be a struct, not a class
C. The protocol cannot be implemented by a class
D. The method should return Void, not Bool

Solution

  1. Step 1: Compare protocol method signature with mock method

    The protocol requires execute() to return a Bool, but the mock method returns Void.
  2. Step 2: Identify the mismatch causing error

    This mismatch causes a compile error because the mock does not conform properly.
  3. Final Answer:

    The mock class does not implement the protocol method signature correctly -> Option A
  4. Quick Check:

    Method signature mismatch = error [OK]
Hint: Method signatures must match exactly in mocks [OK]
Common Mistakes:
  • Ignoring return type mismatch
  • Thinking class vs struct matters here
  • Believing protocols can't be implemented by classes
5. You want to test a view controller that depends on a network service. Which approach correctly uses a mock object and protocol to isolate the test?
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?
hard
A. It allows testing the view controller without real network calls
B. It speeds up the real network requests
C. It automatically updates the UI without code
D. It stores data permanently on the device

Solution

  1. Step 1: Understand the use of protocol and mock

    The protocol defines the network service interface. The mock provides test data without real network calls.
  2. Step 2: Identify the testing benefit

    This setup isolates the view controller from real network dependencies, making tests reliable and fast.
  3. Final Answer:

    It allows testing the view controller without real network calls -> Option A
  4. Quick Check:

    Mock isolates tests from real network [OK]
Hint: Mocks avoid real network calls in tests [OK]
Common Mistakes:
  • Thinking mocks speed up real network
  • Assuming UI updates automatically
  • Confusing mocks with data storage
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