Taking XCode Unit Tests For A Spin

I need to learn Objective-C and iOS development for my current work project.  I’ve tried some tutorial apps in XCode but I always end up doing more copy-paste and reading instead of actually learning by doing and stumbling through.

So I decided to learn out in the open by creating a GitHub project, explore-ios, and try to make a simple tip calculator.  I would’ve done a flashlight app, but a) Apple has shut that market down with the built-in flashlight in control center, and b) I wanted something with some basic logic that I could write unit tests for.  Oh, and c) the UI will have to be crazy simple.

I really love automated testing.  Code without tests makes me…uncomfortable.  Thankfully, when I started a new iOS project and selected the utility app template, I got a test section for free!  It looked promising:

File Explorer with Unit Tests Highlighted

And it comes with a pretty basic test file:

Gotcha #1 – When I went to add my first test of my own though, I ran into my first big “gotcha” – by convention, XCode finds test methods by a prefix convention; all of your test methods have to start with “test.”  This was a tremendously frustrating find, since coming from .NET and NUnit / XUnit testing, I’m used to prefixing tests with “can” or “should” or something similar.  And there don’t appear to be any docs on the subject from my Googling, just some basic references here and here.

You also don’t have to declare your test methods in the implementation section of your test class, which surprised me, but I suspect that will make more sense as my knowledge of Objective-C grows.

So I moved on.  I wrote a test first to take a 20% tip from $20, and in the spirit of TDD just had my new TipCalculator class return a hard-coded 4 before building out the rest of my tests.

Gotcha #2 – Your tests actually require a reloading of your application in the iOS simulator every time, AND the best way to execute your tests is with the ⌘U shortcut as opposed to the Test Navigator UI.

Gotcha #3 – Once I figured out test execution, I hit one last surprise, but this one at least gave me a hint at what the problem was.  In using the XCTAssertEqual operation, you aren’t getting any implicit casting and comparison done for you – if the result is a double, you need to specify the expectation as the same type.  Again, I’m assuming this has nothing to do with XCTAssertEqual and everything to do with the language, but I’m still learning.

The message you get though is quite amusing – I was beginning to doubt my basic understanding of math:

Failure with Implicit Cast

But a quick explicit cast clears everything up:

Success With Explicit Cast

So that’s it!  I hope these gotchas save you the time it took me to get up and running with unit testing in XCode 5.