Articles, podcasts and news about Swift development, by John Sundell.

Capturing multiple values in mocks

Published on 08 Mar 2018
Discover page available: Unit Testing

When capturing values in mocks, using an array (instead of just a single value) makes it easy to verify that only a certain number of values were passed.

Perfect for protecting against "over-calling" something.

class UserManagerTests: XCTestCase {
    func testObserversCalledWhenUserFirstLogsIn() {
        let manager = UserManager()

        let observer = ObserverMock()

        // First login, observers should be notified
        let user = User(id: 123, name: "John")
        XCTAssertEqual(observer.users, [user])

        // If the same user logs in again, observers shouldn't be notified
        XCTAssertEqual(observer.users, [user])

private extension UserManagerTests {
    class ObserverMock: UserManagerObserver {
        private(set) var users = [User]()

        func userDidChange(to user: User) {

Support Swift by Sundell by checking out this sponsor:


Raycast: Take the macOS Spotlight experience to the next level: Create Jira issues, manage GitHub pull requests and control other tools with a few keystrokes. Easily automate every-day tasks and boost your developer productivity by downloading Raycast for free.