I wanted to write a post on Mac unit testing. I have been making my first attempts to do some test driven development, and have found a bunch of great resources. Some are very specific to the environment I’m using (coding Objective C and Cocoa on Mac OS 10.4 with Xcode 2.3) and some are general unit testing and other testing resources. I’m curious how these resources apply to both older and new versions (e.g. do these all work the same on Leopard or Xcode 3.0?), but I’m also commenting on how some older resources work in the new versions. For instance, you’ll find a good number of testing resources that refer to a time when OCUnit was not bundled with Xcode.
Unit testing on CocoaDev is a great place to start. It notes that OCUnit is now shipping with Mac OS 10.4 and Xcode 2.1. From a number of online reviews UnitKit seemed like the main competitor for OCUnit (and definitely has a better name). However, with the bundling of OCUnit, its creator Duncan Davidson decided to extend it further only by sending in patches to OCUnit. So once, you’ve decided on OCUnit, how do you use it?
There are one or two good introductions to OCUnit and one great one. Note that if you are using Xcode 2.3, the steps to ensure OCUnit is working in your project are basically the same (add a new target, add in the framework and create a new group for the test cases), except that your test target will be type “Cocoa > Unit Test Bundle” not “”Cocoa > Test Framework“”. Similarly, when you are creating a test case, the file that you add will be of will be of type “Cocoa > Objective-C test case class” not “ ”Cocoa > Objective-C SenTestCase subclass“. A lot of the links on this page you’ll find on the references and further reading section of Sen:te’s OCUnit page. Little known fact: Sen:te comes from a Go-term roughly meaning getting one step ahead. (and more obviously, adding the initials of the term to do the word itself gives you a bunch of functions with ”teST“ in them.)
All of these intros take a (perfectly well coded and working) app that exists already and add some tests on top. What would have made these intros better is to have taken a real test driven development approach: write the tests first and the code then the app around them.
A great general introduction to xUnit best practices is xUnit Patterns. It seems pretty exhaustive and I’ve found a few hours of good browsing there. It’s pretty early days for me but I’m enjoying reading a section (or two … or three) and trying out the principles in Xcode and OCUnit.