Ben Ford

benford.me

OCUnit Call Stack

OCUnit

OCUnit is the standard unit testing framework that is built into current versions of XCode. The OCUnit SDK is called SenTestingKit, which is a little confusing, but whatever. The biggest drawback to using OCUnit (or SenTestingKit) is you cannot get a call stack (i.e. back trace) when tests fail.

Hey Call Stack

Getting a hold of the NSException object is key to printing the call stack. After a bit of poking around in the headers, I found a notification called SenTestCaseDidFailNotification, which gives you an array of NSExceptions that occurred during test failure.

Code Sample

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@implementation TestCase
- (void)setUp
{
    [super setUp];

    [[NSNotificationCenter defaultCenter] addObserver:self
                  selector:@selector(didFailTest:)
                  name:SenTestCaseDidFailNotification object:nil];
}

- (void)didFailTest:(NSNotification *)notification
{
    SenTestCaseRun *theRun = notification.object;

    for (NSException *exception in theRun.exceptions) {
        NSLog(@"Exception: %@ - %@", exception.name, exception.reason);
        NSLog(@"\n\nCALL STACK: %@\n\n",exception.callStackSymbols);
    }
}
@end

Voila

OCUnit is a bit obscure, but it’s integration into XCode makes it very fast to use—the ⌘U shortcut in XCode is fantastic. This is about the only advantage over GHUnit (another great testing framework), and it is the biggest reason I keep using it.

OCUnit is open-source, and I’ve put this on my list of “code to read”.