Unit Testing on the IPhone
Writing unit tests for an IPhone application is unfortunately a bit more involved than it need be. Here’s how you can get it going for your project (it’s really worth your while doing this at the start of the project, and writing tests as you implement new features but you already know that, right?).
Google have a project called Google Toolbox for Mac located at http://code.google.com/p/google-toolbox-for-mac. Download the latest version and unpack it directly into your project. Rename the directory to google-toolbox-for-mac (it will make it easier to follow along).
Open your project in XCode and then choose Project > New Target... Pick Cocoa Touch Application as the template and name the target Unit Tests. Choose Project > Set Active Target > Unit Tests.
Choose Project > Add to Project... and pick the following files (make sure each are added to the Unit Tests target):
google-toolbox-for-mac/UnitTesting/GTMIPhoneUnitTestMain.m
google-toolbox-for-mac/UnitTesting/GTMIPhoneUnitTestDelegate.m
google-toolbox-for-mac/UnitTesting/GTMIPhoneUnitTestDelegate.h
google-toolbox-for-mac/UnitTesting/GTMSenTestCase.m
google-toolbox-for-mac/UnitTesting/GTMSenTestCase.h
google-toolbox-for-mac/GTMDefines.h
Right-click on Unit Tests in the Targets group and choose Add > New Build Phase > New Run Script Build Phase
Paste this text into the Script box:
${INPUT_FILE_DIR}/google-toolbox-for-mac/UnitTesting/RunIPhoneUnitTest.sh
Try a build now (Cmd-B) and look in the build log. You should see a line like this:
Executed 0 tests, with 0 failures (0 unexpected) in 0.002 (0.002) seconds
Switch back to your normal target and verify that it still builds OK. This is probably a good time to commit everything into source control.
Adding a unit test
Choose File > New File... and select Objective-C test case class from the Mac OS X Cocoa group. Call it FooTest.m if you’re testing a Foo class. Edit the FooTest.h file and replace the existing #import line with:
#import "GTMSenTestCase.h"
That’s it! Add individual test methods and run the tests by doing a build (Cmd-B)