Complete the code to create a stub class that returns a fixed value.
class UserServiceStub: UserServiceProtocol { func fetchUser() -> User { return [1] } }
The stub returns a fixed User instance with name "TestUser" to simulate data.
Complete the code to verify the mock method was called once.
class UserServiceMock: UserServiceProtocol { var fetchUserCalled = false func fetchUser() -> User { fetchUserCalled = true return User(name: "MockUser") } } let mock = UserServiceMock() _ = mock.fetchUser() assert([1] == true)
We check the mock's property fetchUserCalled to confirm the method was called.
Fix the error in the mock class to count how many times fetchUser is called.
class UserServiceMock: UserServiceProtocol { var fetchUserCallCount = 0 func fetchUser() -> User { [1] return User(name: "MockUser") } }
Increment the call count by 1 each time fetchUser is called using += 1.
Fill both blanks to create a stub that returns a user with a dynamic name and verify the name.
class UserServiceStub: UserServiceProtocol { var userName: String init(name: String) { self.userName = [1] } func fetchUser() -> User { return User(name: [2]) } } let stub = UserServiceStub(name: "Alice") let user = stub.fetchUser() assert(user.name == "Alice")
The initializer assigns the parameter 'name' to the property 'userName'. The fetchUser returns a User with 'self.userName'.
Fill all three blanks to create a mock that records calls and returns a stubbed user.
class UserServiceMock: UserServiceProtocol { var fetchUserCallCount = 0 var stubUser: User init(stubUser: User) { [1] = stubUser } func fetchUser() -> User { [2] return [3] } } let stub = User(name: "Bob") let mock = UserServiceMock(stubUser: stub) _ = mock.fetchUser() assert(mock.fetchUserCallCount == 1) assert(mock.stubUser.name == "Bob")
The initializer assigns stubUser to self.stubUser. The fetchUser increments call count and returns self.stubUser.