Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Test-Driven iOS Development with Swift

You're reading from   Test-Driven iOS Development with Swift Create fully-featured and highly functional iOS apps by writing tests first

Arrow left icon
Product type Paperback
Published in Feb 2016
Publisher Packt
ISBN-13 9781785880735
Length 218 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Dr. Dominik Hauser Dr. Dominik Hauser
Author Profile Icon Dr. Dominik Hauser
Dr. Dominik Hauser
Arrow right icon
View More author details
Toc

Building your first automatic unit test

If you have done some iOS development (or application development in general) before, the following example might seem familiar to you.

You are planning to build an app. You start collecting features, drawing some sketches, or your project manager hands the requirements to you. At some point, you start coding. After you have set up the project, you start implementing the required features of the app.

Let's say the app is an input form, and the values the user puts in have to be validated before the data can be sent to the server. The validation checks, for example, whether the e-mail address looks like it's supposed to and the phone number has a valid format. You implement the form and check whether everything works. But before you can test, you need to write code that presents the form on the screen. Then, you build and run your app in the iOS simulator. The form is somewhere deep in the view hierarchy. So, you navigate to this view and put the values into the form. It doesn't work. Next, you go back to the code and try to fix the problem. Sometimes, this also means that you need to run the debugger, and build and run to check whether the code still has errors.

Eventually, the validation works for the test data you put in. Normally, you would need to test for all possible values to make sure that the validation not only works for your name and your data but also for all valid data. But there is this long list of requirements on your desk, and you are already running late. The navigation to the form takes three taps in the simulator, and putting in all the different values just takes too long. You are a coder after all.

If only a robot could perform this testing for you.

What are unit tests?

Automatic unit tests act like a robot for you. They execute code but without the need of navigating to the screen with the feature to test. Instead of running the app over and over again you write tests with different input data and let the computer test your code in the blink of an eye. Let us see how this works in a simple example.

Implementing a unit test example

Open Xcode and go to File | New | Project. Navigate to iOS | Application | Single View Application, and click on Next. Put in the name FirstDemo, select the Swift language, iPhone for Devices, and check Include Unit Tests. Uncheck Use Core Data and Include UI Tests, and click on Next. The following screenshot shows the options in Xcode:

Implementing a unit test example

Xcode sets up a completely ready project for development in addition to a test target for your unit tests. Open the FirstDemoTests folder in Project Navigator. Within the folder, there are two files: FirstDemoTests.swift and Info.plist. Select FirstDemoTests.swift to open it in the editor.

What you see here is a test case. A test case is a class comprising several tests. It's good practice to have a test case for each class in the main target.

Let's go through this file step by step:

import XCTest
@testable import FirstDemo

Every test case needs to import the XCTest framework. It defines the XCTestCase class and the test assertions that you will see later in this chapter.

The second line imports the FirstDemo module. All the code you write for the app will be in this module. By default, classes, structs, enums, and their methods are defined as internal. This means that they can be accessed within the module. But the test code lives outside of the module. To be able to write tests for your code, you need to import the module with the @testable keyword. This keyword makes the internal elements of the module accessible to the test case.

Next we'll take a look at the class declaration:

class FirstDemoTests: XCTestCase {

Nothing special here. This defines a class FirstDemoTests as a subclass of XCTestCase.

The first two methods in the class are as follows:

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }
    
    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

The setUp() method is called before the invocation of each test method in the class. Here, you can insert code that should run before each test. You will see an example of this later in this chapter.

The opposite of setUp() is tearDown(). This method is called after the invocation of each test method in the class. If you need to clean up after your tests, put the necessary code in this method.

There are two test methods in the template provided by Apple:

    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }
    
    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measureBlock {
            // Put the code you want to measure the time of here.
        }
    }
    
}

The first method is a normal test. You will use this kind of test a lot in the course of this book.

The second method is a performance test. It is used to test methods or functions that perform time-critical computations. The code you put into measureBlock is called several times, and the average duration is measured. Performance tests can be useful when implementing or improving complex algorithms and to make sure that their performance does not decline. We will not use performance tests in this book.

All the test methods that you write have to have the test prefix; otherwise, the test case can't find and run them. This behavior allows easy disabling of tests: just remove the test prefix of the method name. Later, you will take a look at other possibilities to disable some tests without renaming or removing them.

Now, let's implement our first test. Let's assume that you have a method that counts the vowels of a string. A possible implementation could look like this:

func numberOfVowelsInString(string: String) -> Int {
    let vowels: [Character] = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
    
    var numberOfVowels = 0
    for character in string.characters {
        if vowels.contains(character) {
            ++numberOfVowels
        }
    }
    
    return numberOfVowels
}

Add this method in the ViewController class in ViewController.swift.

This method does the following things:

  • First, an array of characters is defined containing all the vowels in the English alphabet.

    Tip

    Note that without the [Character] type declaration right after the name of the constant, this would be created as an array of strings, but we need an array of characters here.

  • Next, we define a variable to store the number of vowels. The counting is done by looping over the characters of the string. If the current character is contained in the vowels array, numberOfVowels is increased by one.
  • Finally, numberOfVowels is returned.

Open FirstDemoTests.swift, and remove the two test methods (the methods with the test prefix). Add the following method to it:

func testNumberOfVowelsInString_ShouldReturnNumberOfVowels() {
    let viewController = ViewController()
    
    let string = "Dominik"
    
    let numberOfVowels = viewController.numberOfVowelsInString(string)
    
    XCTAssertEqual(numberOfVowels, 3, "should find 3 vowels in Dominik")
}

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

This test creates an instance of ViewController and assigns it to the constant viewController. It defines a string to use in the test. Then, it calls the function that we want to test and assigns the result to a constant. Finally, the test method calls the XCTAssertEqual(_, _) function to check whether the result is what we expected.

To run the tests, go to Product | Test, or use the command + U shortcut. Xcode compiles the project and runs the test. You should see something similar to what is shown in this screenshot:

Implementing a unit test example

The green diamond with a checkmark on the left-hand side of the editor indicates that the test passed. So, this is it. This is your first unit test. Step back for a moment and celebrate. This could be the beginning of a new development paradigm for you.

Now that we have a test that proves that the method does what we intended, we are going to improve the implementation. The method looks like it has been translated from Objective-C. But this is Swift. We can do better. Open ViewController.swift, and replace the numberOfVowelsInString(_:) method with this swift implementation:

func numberOfVowelsInString(string: String) -> Int {
    let vowels: [Character] = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
          
    return string.characters.reduce(0) { $0 + (vowels.contains($1) ? 1 : 0) }
}

Here, we make use of the reduce function, which is defined in the array type. Run the tests again (command + U) to make sure that this implementation works like the one earlier.

Before we move on, let's recap what we have seen here. Firstly, we learned that we could easily write code that tests our code. Secondly, we saw that a test helped improve the code because we now don't have to worry about breaking the feature when changing the implementation.

To check whether the result of the function is as we expect, we used XCTAssertEqual(_, _). This is one of many XCTAssert functions that are defined in the XCTest framework. The next section describes the most important ones.

Important built-in assert functions

Each test needs to assert some expected behavior. The use of the XCTAssert functions tells Xcode what should happen. A test method without an XCTAssert function will always pass as long as it compiles. The most important assert functions are:

  • XCTAssertTrue(_:_:file:line:): Asserts that an expression is true
  • XCTAssertFalse(_:_:file:line:): Asserts that an expression is false
  • XCTAssertEqual(_:_:_:file:line:): Asserts that two expressions are equal
  • XCTAssertEqualWithAccuracy(_:_:accuracy:_:file:line:): Asserts that two expressions are the same, taking into account the accuracy defined in the accuracy parameter
  • XCTAssertNotEqual(_:_:_:file:line:): Asserts that two expressions are not equal
  • XCTAssertNil(_:_:file:line:): Asserts that an expression is nil
  • XCTAssertNotNil(_:_:file:line:): Asserts that an expression is not nil
  • XCTFail(_:file:line:): Always fails

Tip

To take a look at the full list of the available XCTAssert functions, press control, and click on the word XCTAssertEqual in the test that you have just written. Then, select Jump to Definition in the pop-up menu.

Note that all the XCTAssert functions could be written using XCTAssertTrue(_:_:file:line:). For example, these two lines of code are equivalent to each other:

// This assertion is equivalent to...
XCTAssertEqual(2, 1+1, "2 should be the same as 1+1")

// ...this assertion
XCTAssertTrue(2 == 1+1, "2 should be the same as 1+1")

In all the XCTAssert functions, the last three parameters are optional. To take a look at an example for the use of all the parameters, let's check out what a failing test looks like in Xcode. Open FirstDemoTests.swift, and change the expected number of vowels from 3 to 4:

XCTAssertEqual(numberOfVowels, 4, "should find 4 vowels in Dominik")

Now, run the tests. The test fails. You should see something like this:

Important built-in assert functions

Xcode tells you that something went wrong with this test. Next to the test function, there is a red diamond with x on it. The same symbol is in the line that actually failed. Beneath this line is the explanation of what actually went wrong, followed by the string you provided in the test. In this case, the first parameter, numberOfVowels, is Optional(3), and the second parameter is Optional(4). The Optional(3) parameter is not equal to Optional(4); therefore, the test fails.

As mentioned earlier, XCTAssertEqual(…) has two more parameters—file and line. To take a look at the use of these additional parameters, go to View | Debug Area | Activate Console to open the debug console. If the debug area is split in half, click on the second right-most button in the bottom-right corner to hide the variables' view:

Important built-in assert functions

We have only one test at the moment, and the debug output is already kind of messy. Later in this chapter, we will learn that there is a better UI for the same information in Xcode.

There is one line in the output that shows the failing test:

/Users/dom/Documents/development/book/FirstDemo/FirstDemoTests/FirstDemoTests.
 swift:31: error: -[FirstDemoTests.FirstDemoTests testNumberOfVowelsInString_ShouldReturnNumberOfVowels] : XCTAssertEqual failed: ("Optional(3)") is not equal to ("Optional(4)") - should find 4 vowels in Dominik

The output starts with the file and line parameters where the failing tests are located. With the file and line parameters of the XCTAssert functions, we can change what is printed there. Go back to the test method, and replace the assertion with this:

XCTAssertEqual(numberOfVowels, 4, "should find 4 vowels in Dominik", file: "FirstDemoTests.swift", line: 24)

The test method starts at line number 24.

With this change, the output is as follows:

FirstDemoTests.swift:24: error: -[FirstDemoTests.FirstDemoTests testNumberOfVowelsInString_ShouldReturnNumberOfVowels] : XCTAssertEqual failed: ("Optional(3)") is not equal to ("Optional(4)") - should find 4 vowels in Dominik

The debug output of the test now shows the filename and line number that we specified in the assertion function.

Tip

As I mentioned earlier, in all XCTAssert functions, the last three parameters are optional. In cases where you don't need the message because the used assertion function makes clear what the failure is, you can omit it.

Before we move on with the introduction to TDD, change the test so that is passes again (either by changing the used test string or the expected number of vowels).

You have been reading a chapter from
Test-Driven iOS Development with Swift
Published in: Feb 2016
Publisher: Packt
ISBN-13: 9781785880735
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime