Writing tests using XCTest

The following diagram illustrates how you can build a test using the XCTest framework in Swift:

When running tests, XCTest finds all the test classes in our application. Each test class is a subclass of XCTestCase [1]. XCTest runs the setUp() method [2] and then all of the class's test methods.

Each test method [3] that implements a test always has the prefix test, takes no parameters, and returns no values. A test method may have an optional block called addTeardownBlock(_:) for us to add additional cleanup code. This is useful if we need to destroy a resource created locally in the test method.

If XCTest runs out of all the test methods, it will run the class teardown method [4] and move on to the next class. This process is repeated until all test classes are executed.

The static array allTests [5] is an object XCTest used to know which tests to execute. It is there to keep the tests compatible for a Linux environment. If you would like to run a Swift test in Linux, you'll need to create the LinuxMain.swift file that calls allTests. The LinuxMain.swift file shown here is automatically generated by Kitura CLI:

// LinuxMain.swift file for Linux
import XCTest

@testable import ApplicationTests

XCTMain([
testCase(RouteTests.allTests), // [1]
])

LinuxMain.swift acts as the test runner for Linux platforms. It calls XCMain(_:) which lists all your test cases [1].