Swift Package Manager just went through a massive refactoring and adds support for testing using XCTest on OSX and Linux. It is not yet available on the latest snapshot but we can always try it out by building swiftpm.
Get the latest swift pm
Install the latest snapshot and run the commands below to build swiftpm, should take about a minute.
The last two steps will create aliases to swift-build and swift-test (Yes, swiftpm outputs two exectuables now). This is not required but is convienent than using the entire path.
Set up tests structure
I’ll be using the package I created earlier which is a simple GET client.
- Create a folder
Tests in root of your swift package
Tests create another folder which will be a test-module, you can create as many test-module (ie folders) you need in case your package contains more than one target
- According to the proposal it would be possible to directly write test if you have only one target
- Create a .swift file to write your tests inside that test-module dir
Write Test Cases
- Import the package you want to test and
- The method name should begin with “test”
- Here is an example :
Now run swift build and swift test to build the package and run the tests. Use the aliases created above to use the swift-build and swift-test we built above.
Tests on Linux
For Linux users, theres a little more wiring up to do. First create an extension to your test case conforming to
XCTestCaseProvider and return all the test methods.
Now go to the Tests directory and create a file named
LinuxMain.swift and write the following :
ie import all test-modules by writing
<test-module-dirname>test and call the constructor to all your
XCTestCase subclasses inside
XCTMain method. Now swift-test should work for linux too.
I was able to run the test cases on Travis-CI’s Ubuntu distro using this .travis.yml :
Since swift-test is not currently available in the toolchain, I built swiftpm on travis itself. (Hacks :>)
The package I used is available here : https://github.com/aciidb0mb3r/SimpleGetClient
PS : It was probably a little too early to write this post 😂 but things shouldn’t change a lot.