Challenge - 5 Problems
Mock Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate1:30remaining
Why use protocols for mocking in Swift?
In Swift, why do developers often use protocols when creating mock objects for testing?
Attempts:
2 left
💡 Hint
Think about how protocols help replace real objects with test doubles.
✗ Incorrect
Protocols in Swift define required methods and properties. Mocks implement these protocols to stand in for real objects during tests, enabling controlled and isolated testing.
❓ ui_behavior
intermediate1: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 ???
}
}Attempts:
2 left
💡 Hint
Success means the login method should indicate a positive result.
✗ Incorrect
Returning true simulates a successful login, allowing the UI to proceed as if authentication succeeded.
❓ lifecycle
advanced2: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?
Attempts:
2 left
💡 Hint
Think about test isolation and avoiding shared state.
✗ Incorrect
Creating a fresh mock in setUp() ensures each test starts with a clean state, preventing tests from affecting each other.
📝 Syntax
advanced2: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
}Attempts:
2 left
💡 Hint
Check method signature matches protocol exactly.
✗ Incorrect
Option A correctly implements the protocol method with matching return type. Others either have wrong return type, missing protocol conformance, or wrong method signature.
🔧 Debug
expert2: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?
Attempts:
2 left
💡 Hint
What does fatalError() do when called?
✗ Incorrect
fatalError() immediately stops program execution with a crash. Using it in a mock method causes tests to crash if that method is called.