Setup unit test for Swift command line app and CI with Travis

1. Adding test bundle for command line app

Writing unit tests for iOS or Cocoa App is way more straight forward rather than command line app. When you create iOS/Cocoa App, then you already got a test bundle come with free. So you don’t have to do setup or anything. You just simply add more test cases.

There’re couple of suggestions on StackOverFLow, but didn’t work for me. And here is the setup that would allow me write test cases for command line app.

  • Step 1: Open Xcode, go to `Editor` -> `Add Target` -> then choose `OSX Unit Testing Bundle`, then just next, next ..
  • Step 2: Edit scheme, click on `Test` -> `+` button to add

That’s all. Now all of your code would be available for test.

**TIP**:

  • Normally any command line app would require some arguments. And your build would fail if you don’t provide some default argument for the purpose of build. You can do so by `Edit Scheme` -> go to `Run` and add `arguments passed on launch`
  • One more tip, in order to use all stuff from you code you gonna need to use `@testable` to import the module contain you code

2. Adding CI (Travis)

Implement a CI for an Xcode project might not very clear for many people. The reason is because there’re not many resouce around it. Normally it would require many failed experiments to make it work with your cases. And here is the setup that work with mine.

I used the Swift command line app as a part of ruby web server. And here is it (`.travis.yml`)

# .travis.yml
matrix:
  include:
    - os: osx
      language: objective-c
      xcode_project: YourProjectName.xcodeproj
      xcode_scheme: YourProjectName
      script: cd YourProjectName && xcodebuild -scheme YourProjectName test
      osx_image: xcode7.2
      before_install:
        - rvm install 2.2.2
        - rvm use 2.2.2 --default
        - gem install bundler
        - bundle config build.eventmachine --with-cppflags=-I/usr/local/opt/openssl/include

Look pretty simple right. From the config above the most important line is this one `cd YourProjectName && xcodebuild -scheme YourProjectName test` -> this mean go into your Swift project and do the build from therer and run the test. For the rest you can look into travis tutorial, they’re pretty easy to understand. Again your project would be different but the structure gonna be quite similar.

You just got the project setup and CI ready. Now time to add some meaningful unit tests.

Advertisements
Setup unit test for Swift command line app and CI with Travis

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s