This page contains information about iOS unit test case templates that I use. Instructions for downloading and installing are at the bottom of this page.

Basic Unit Test Case File Template

This template is a basic unit test case file. I prefer to combine header and implementation into a single file for unit test cases.

#import <SenTestingKit/SenTestingKit.h>
#import <OCMock/OCMock.h>  // Included now for use later
#import "YourObject.h"

@interface YourObjectTests : SenTestCase
@property (strong, nonatomic) YourObject * yourObject;

@implementation YourObjectTests

- (void)setUp {
    self.yourObject = [[YourObject alloc]init ];

- (void)tearDown {
    self.yourObject = nil;

- (void)testYourObjectInstantiation
    STAssertNotNil(self.yourObject, @"YourObject was not created.");

Mock Dependent Object Template

Any test case can create a mock object to eliminate the need to create other dependent objects.

- (void)testMethodWithOtherObjectDependency {
    id mock = [OCMockObject mockForClass:[OtherObject class]];
    self.yourObject.dependency = mock;
    // ... perform testing on object 
    //     now that other object is mocked

Partial Mock Template

A partial mock is used when a method being tested calls other methods on the same object.

- (void)testMethodCallingOtherMethod {
    id mock = [OCMockObject partialMockForObject:self.yourObject];
    [[mock expect]otherMethod:[OCMArg any]];
    [mock methodUnderTest];
    // ... Other success assertions
    [mock verify]; //Ensure that expected method was called

Installing Custom Xcode Templates

Unit testing becomes quicker and easier if you have some custom Xcode file templates installed. The default Xcode Objective-C test case class file template provided with Xcode 4.5 leaves a lot to be desired. I’ve created a better template and posted it on Github. This provides boiler plate for things like including OCMock, setUp and tearDown methods, and so forth.

To install custom Xcode File Templates:

  1. Download the xcode-file-templates from Github.
  2. Copy the “Custom Unit Tests” directory to the Xcode user templates directory. This should be in your user directory at ~/Library/Developer/Xcode/Templates. If this directory doesn’t exist, then create it.
    Note that ~/Library is typically hidden in Finder. You can use Finder’s “Go To Folder” to get there.
  3. You can rename the “Custom Unit Tests” directory to something else if you wish. Xcode will display the name of this directory in the File New dialogs. If you don’t change it, then is should display “Custom Unit Tests”.

That’s it. You may need to restart Xcode before seeing the changes. Now when you create a new file, you will see “Custom Unit Tests” on the left. Select it, and then choose an Objective-C test case class.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.