Unit testing with Swift

Unit test classes in Swift derive from XCTestCase. You’ll need to import XCTest.

So for example

import XCTest

class MvvmTestTests: XCTestCase {
}

Test functions need to be prefixed with test so for example, if we assume we have a global function like this

func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}

then we might have a test like this

func testAdd() throws {
    XCTAssertEqual(5, MyApp.add(2, 3))
}

Before we can test our add function we need to make the application code available to the test code, to do this after the import XCTest line add

@testable import MyApp

This actually allows our tests to access our code without having to mark all the code as public.

As you’ve seen we use XCTAssertEqual to assert our expectations against actual.

Measuring Performance

We can wrap our code, within a test, using

self.measure {
}

So for example (whilst a little pointless on our add function) we can measure performance like this

self.measure {
   _  = MvvmTest.add(2, 3)
}

We can also apply options to the measure function

let option = XCTMeasureOptions()
option.iterationCount = 100
self.measure(options: option) {
    _  = MvvmTest.add(2, 3)
}

In this case we’ll run the measure block 100 + 1 times. The iteration actually ignores the first run (hence the + 1) this tries to remove cold start times.

Running our tests

In Xcode, select the Test Navigator, this should show you all the tests found. Simply select either a single test or group of tests and right mouse click. Select the Run option and your tests will run.