What is the best way to unit test Objective-C code?

Solution 1:

Xcode includes XCTest, which is similar to OCUnit, an Objective-C unit testing framework, and has full support for running XCTest-based unit tests as part of your project's build process. Xcode's unit testing support is described in the Xcode Overview: Using Unit Tests.

Back in the Xcode 2 days, I wrote a series of weblog posts about how to perform some common tasks with Xcode unit testing:

  • Unit testing Cocoa frameworks
  • Debugging Cocoa framework unit tests
  • Unit testing Cocoa applications
  • Debugging Cocoa application unit tests

Despite using OCUnit rather than XCTest, the concepts are largely the same.

Finally, I also wrote a few posts on how to write tests for Cocoa user interfaces; the way Cocoa is structured makes it relatively straightforward, because you don't have to spin an event loop or anything like that in most cases.

  • Trust, but verify.
  • Unit testing Cocoa user interfaces: Target-Action
  • Unit testing Cocoa user interfaces: Cocoa Bindings

This makes it possible to do test-driven development for not just your model-level code but also your controller-level and even view-level code.

Solution 2:

Check out GHUnit by Gabriel Handford:

"The goals of GHUnit are:

Runs unit tests within XCode, allowing you to fully utilize the XCode Debugger. A simple GUI to help you visualize your tests. Show stack traces. Be installable as a framework (for Cocoa apps) with a simple (or not) target setup; or easy to package into your iPhone project."

Solution 3:

I started using the Google toolbox testing rig for iPhone, and its working out great for me.

google-toolbox-for-mac

Solution 4:

Check out OCUnit. Apple's developer network has a great introduction.

Solution 5:

Note that the Google Toolbox for Mac (GTM) project simply extends/augments Apple's SenTestingKit framework (which is, itself based on OCUnit). As they say on the project site:

GTM has several enhancement to the standard SenTestingKit allowing you to do UI unit testing, automated binding unit testing, log tracking, and unit testing on the iPhone, as well as tools for doing static and dynamic testing of your code.

Note the following comment about user-interface testing:

GTM has extensive support for user interface unit tests. It supports testing both the imaging and/or internal state of almost all of the standard Cocoa/UIKit UI objects, and makes it easy for you to extend this support to your own UI objects.

See their "Code Verification and Unit Testing" page for instructions on how to use it.