Challenge - 5 Problems
Test Doubles Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
The stub replaces the real method with a fixed return value.
✗ Incorrect
The stub class implements the protocol and returns a fixed string. When printData calls fetchData, it prints "Stubbed Data".
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
The mock increments logCount every time log() is called.
✗ Incorrect
The log() method is called twice, so logCount becomes 2 and prints 2.
🔧 Debug
advanced2: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)
Attempts:
2 left
💡 Hint
Check variable scope inside the method.
✗ Incorrect
Inside performAction, a new local variable callCount is declared, shadowing the class property. So the class property never increments.
🧠 Conceptual
advanced2:00remaining
Purpose of a stub in testing
Which statement best describes the purpose of a stub in unit testing?
Attempts:
2 left
💡 Hint
Think about how stubs help isolate code under test.
✗ Incorrect
Stubs provide fixed responses to isolate the tested code from real dependencies, making tests predictable and fast.
❓ Predict Output
expert2: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())
Attempts:
2 left
💡 Hint
Check the order in which methods are called and recorded.
✗ Incorrect
The calls array records ["second", "first"], which does not match the expected ["first", "second"], so verify() returns false.