Swift comes with its own unit testing framework XCTest, let’s take a look at what we need to do to enable unit testing and how we use this library.
Test Package Dependencies
If you created your package via the Wwift package manager your project will be laid out with Sources and Tests folders.
Here’s an example of a library package, notice the .testTarget section
targets: [ .target( name: "MyLib", dependencies: []), .testTarget( name: "MyLibTests", dependencies: ["MyLib"]), ]
Creating a test fixture
Next up we need to import the XCTest library and derive our test fixture/class from XCTestCase, for example
final class MyLibTests: XCTestCase { // tests go here }
Creating a test
Tests are written in test methods within the test case subclass. Test methods have no parameters, no return value and the name should begin with lowercase prefix test, so for example
final class MyLibTests: XCTestCase { func testIsValid() { // test setup and asserts } }
Asserting our tests
The XCTest library prefixes its assertion method with XCT. Hence, we have XCTAssertEqual for example to assert that two values are equal
final class MyLibTests: XCTestCase { func testIsValid() { let a = 1 let b = 1 XCTAssertEqual(a, b) } }