Reviewing Kitura boilerplate tests
Writing tests for server-side Swift projects starting with the Kitura framework will be the same as what you've just learned with the Vapor framework, since both Kitura and Vapor use the same XCTest framework.
If you check out the boilerplate project created with kitura init, you will find more tests there. The first test, testGetStatic, shows you how to test a Kitura server running static content. The second test, testHealthRoute, demonstrates how to test the probing results of health on a Kitura server instance:
Now open the RouteTests.swift file, and you will see a typical XCTestCase implementation:
// ...
class RouteTests: XCTestCase { // [1]
static var port: Int!
static var allTests : [(String, (RouteTests) -> () throws -> Void)] { // [2]
return [
("testGetStatic", testGetStatic)
override func setUp() { // [3]
super.setUp()
HeliumLogger.use()
do {
// ... [not shown]
let app = try App()
RouteTests.port = app.cloudEnv.port
try app.postInit()
Kitura.addHTTPServer(onPort: RouteTests.port, with: app.router)
Kitura.start()
} catch {
XCTFail("Couldn't start Application test server: \(error)")
}
}
override func tearDown() { // [4]
Kitura.stop()
super.tearDown()
}
func testGetStatic() { // [5]
// ... [not shown]
}
func testHealthRoute() { // [6]
// ... [not shown]
}
}
private extension URLRequest { // [7]
// ... [not shown]
}
If you put aside the implementation details in the preceding code, you'll see the high-level constructs of XCTestCase class clearly:
- Declare RouteTests by subclassing from XCTestCase
- Include all tests that contains all target tests (for LINUX compatibility)
- Set up and run a new Kitura server instance
- Stop and tear down the current server instance
- Implement the logic for testing static content
- Implement the probe for the current server instance's health
- Use extensions to include implementation common to both tests
The RouteTests class takes advantage of setUp() and tearDown() methods in implementing a Kitura server instance used by each test. As explained before, each unit test will be independent from each other. You need to set up a new instance of the Kitura server each time a test is executed. The setUp() and tearDown() methods help you avoid writing repetitive code by reusing the server setup and teardown code.
Next, try to run the tests to see what results the two tests output. In Xcode, select the test target:
When you use the command + U command to run the test target in Xcode, the console window prints the following output: