Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Test Doubles in Swift

DZone's Guide to

Test Doubles in Swift

Test doubles are custom dependencies for unit testing. Read on for info and examples on the types of test doubles for Swift.

· Mobile Zone
Free Resource

The purpose of unit testing is checking the expected behaviors of a component, which is called System Under Test (aka SUT). When the SUT has some dependencies, it may be painful to test because you must manage these dependencies somehow. You shouldn't use the same you would use in production, since you would add complexity to your tests. The solution is using custom dependencies which make the SUT easy to test. 

These "custom dependencies" are commonly called "Mock" dependencies. Unfortunately, "Mock" is not a proper name since a custom dependency can behave in a different way, depending on how you want to test the SUT. Gerard Meszaros, in his book "xUnit Test Patterns: Refactoring Test Code," created a list of different types of "Mock" dependencies—the Test Doubles.

Test Doubles

There are different types of Test Double. The order of the following list is from the simplest to the most complex. For this reason, I suggest you understand each Test Double well before reading the next one.

Dummy

A dummy dependency is an object which is not used in your test. Basically, you merely use it to let compile the test.

Example

We can start using a plain Square class which computes its area and can save the value of the area thanks to the protocol SaverProtocol:


protocol SaverProtocol {
    func save(value: Float)
}

class Square {

    private let saver: SaverProtocol

    var side: Float = 0
    var area: Float {
        return pow(self.side, 2)
    }

    init(saver: SaverProtocol) {
        self.saver = saver
    }

    func saveArea() {
        saver.save(value: area)
    }
}

Then, we want to test Square to check if the area computation is right. For this test, we don't care about the method saveArea, since our focus is in the area computation, but the constructor of Square needs a SaverProtocol argument even if we don't use it. Therefore, we can create a Dummy class, which creates an empty implementation of the SaverProtocol method, with the only purpose of compiling our test:

func test_Area() {
    let sut = Square(saver: DummySaver())

    sut.side = 5

    XCTAssertEqual(sut.area, 25)
}

class DummySaver: SaverProtocol {
    func save(value: Float) { }
}

Fake

A Fake dependency has an implementation, but it's a shortcut to increase the speed of the test and decrease its complexity.

Example

We can start with a class UsersRepo, which fetches the users, thanks to UsersServiceProtocol, and has a method to return a friendly message with the count of the entities. For the normal implementation, which is used in production, we fetch the users from a Database—like CoreData, Realm, and so on:

struct User {
    let identifier: String
    let username: String
}

protocol UsersServiceProtocol {
    func fetchUsers() -> [User]
}

class UsersService: UsersServiceProtocol {
    func fetchUsers() -> [User] {
        let users = // execute a query in a Database
        return users
    }
}

class UsersRepo {

    private let users: [User]

    init(usersService: UsersServiceProtocol) {
        self.users = usersService.fetchUsers()
    }

    func usersCountMessage() -> String {
        return "Number of users in the system: \(users.count)"
    }
}

Then, we want to test usersCountMessage to check if it returns the right message. We can't use a database in the test since it would slow the speed of the test and increase its complexity. To avoid a database, we can create a FakeUsersService which returns hardcoded users:

func test_UsersCountMessage() {
    let sut = UsersRepo(usersService: FakeUsersService())

    XCTAssertEqual(sut.usersCountMessage(), "Number of users in the system: 2")
}

class FakeUsersService: UsersServiceProtocol {
    func fetchUsers() -> [User] {
        return [User(identifier: 1, username: "user01"), User(identifier: 2, username: "user02")]
    }
}

Do not be afraid to use hardcoded values for the tests. It's not production code, you have to find a good trade-off to have fast and well-written tests.

Stub

A Stub dependency provides canned answers about the method calls made by the SUT—like a boolean flag which allows you to check if an internal method has been called.

Example

We can reuse the example used for Fake:

class UsersRepo {

    private let users: [User]

    init(usersService: UsersServiceProtocol) {
        self.users = usersService.fetchUsers()
    }

    func usersCountMessage() -> String {
        return "Number of users in the system: \(users.count)"
    }
}

Now, we want to test if the constructor loads the users calling fetchUsers. To achieve it, we can use a StubUsersService which provides a boolean property isFetchUsersCalled to check if fetchUsers is called:

func test_Init() {
    let stubUsersService = StubUsersService()

    _ = UsersRepo(usersService: stubUsersService)

    XCTAssertTrue(stubUsersService.isFetchUsersCalled)
}

class StubUsersService: UsersServiceProtocol {

    var isFetchUsersCalled = false

    func fetchUsers() -> [User] {
        isFetchUsersCalled = true

        return []
    }
}


Spy

A Spy dependency is a more powerful version of the Stub one. It provides information based on how its methods are called, like the parameters values or how many times the method is called.

Example

We can reuse the example used for Dummy:

class Square {

    private let saver: SaverProtocol

    var side: Float = 0
    var area: Float {
        return pow(self.side, 2)
    }

    init(saver: SaverProtocol) {
        self.saver = saver
    }

    func saveArea() {
        saver.save(value: area)
    }
}

Now, we want to test the method saveArea to check if it calls the method save of SaverProtocol just once and with the area as a parameter:

func test_SaveArea() {
    let saver = SpySaver()
    let sut = Square(saver: saver)
    sut.side = 5

    sut.saveArea()

    XCTAssertEqual(saver.saveCallsCount, 1)
    XCTAssertEqual(saver.saveValue, 25)
}

class SpySaver: SaverProtocol {
    var saveCallsCount = 0
    var saveValue: Float?

    func save(value: Float) {
        saveCallsCount += 1
        saveValue = value
    }
}

Mock

Looking at the test used to explain Spy, you can notice that, once you have a lot of parameters to check, your test becomes difficult to read and you have to expose a lot of SpySaver properties.

A Mock dependency helps you to clean your test since you check the values internally. 

Example

For the sake of explanation, we can reuse the test used for Spy:

func test_SaveArea() {
    let saver = SpySaver()
    let sut = Square(saver: saver)
    sut.side = 5

    sut.saveArea()

    XCTAssertEqual(saver.saveCallsCount, 1)
    XCTAssertEqual(saver.saveValue, 25)
}

class SpySaver: SaverProtocol {
    var saveCallsCount = 0
    var saveValue: Float?

    func save(value: Float) {
        saveCallsCount += 1
        saveValue = value
    }
}

We refactor it using a Mock dependency instead of a Spy one. We move the asserts inside the MockSaver method verify and keep both saveCallsCount and saveValue private:

func test_SaveArea() {
    let saver = MockSaver()
    let sut = Square(saver: saver)
    sut.side = 5

    sut.saveArea()

    saver.verify(saveCallsCount: 1, saveValue: 25)
}

class MockSaver: SaverProtocol {
    private var saveCallsCount = 0
    private var saveValue: Float?

    func save(value: Float) {
        saveCallsCount += 1
        saveValue = value
    }

    func verify(saveCallsCount: Int, saveValue: Float) {
        XCTAssertEqual(saveCallsCount, 1)
        XCTAssertEqual(saveValue, 25)
    }
}

You can find an interesting talk about Mock objects here.

Mastering Test Doubles is a good step towards the perfect unit testing. Each test has its complexity and you must figure out which Test Double suits better your needs.

Topics:
swift ,ios ,test doubles ,unit testing ,mobile ,mobile app development

Published at DZone with permission of Marco Santarossa, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}