Contents

Test Doubles In Swift


A keen developer writes a lot of unit tests to cover the code to use in production. Unfortunately, a component can sometimes be difficult to test because of its dependencies, and you would be tempted to give up. Hang on, Test Doubles are what you need to make a test easy to write.

Overview

The purpose of unit testing is checking the expected behaviours 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 in somehow. You shouldn’t use the same which 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 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 easier to the most complex. For this reason, I suggest you to understand well each Test Double 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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
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 of 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 SaverProtocol method, with the only purpose to let compile our test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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 its 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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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 to calls made by the SUT.

Example

We can reuse the example used for Fake:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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 usersCountMessage is using the value returned by UsersServiceProtocol. To achieve it, we can use a StubUsersService where we can force the value returned by fetchUsers:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
func test_usersCountMessage_returnsRightValue() {
    let stubUsersService = StubUsersService()
    stubUsersService.forcedUsersResult = [User(identifier: "1230-4444", username: "Test")]
    let sut = UsersRepo(usersService: stubUsersService)

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

class StubUsersService: UsersServiceProtocol {

    var forcedUsersResult: [User]!

    func fetchUsers() -> [User] {
        return forcedUsersResult
    }
}

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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 parameter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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(self.saveCallsCount, saveCallsCount)
        XCTAssertEqual(self.saveValue, saveValue)
    }
}

You can find an interesting talk about Mock objects here.

Conclusion

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.