Unit Testing Tutorial for iOS: Xcode 4 Quick Start Guide

A unit testing tutorial for iOS and xCode 4. By .

Leave a rating/review
Save for later
Share
You are currently viewing page 3 of 3 of this article. Click here to view the first page.

Simple Test Case with OCMock

Now we need to add some test cases that use OCMock to our SampleTestCase. Update SampleTestCase.m to look like this:

#import <GHUnitIOS/GHUnit.h>
#import <OCMock/OCMock.h>

@interface SampleLibTest : GHTestCase { }
@end

@implementation SampleLibTest

- (void)testSimplePass {
    // Another test
}

- (void)testSimpleFail {
    GHAssertTrue(NO, nil);
}

// simple test to ensure building, linking, 
// and running test case works in the project
- (void)testOCMockPass {
    id mock = [OCMockObject mockForClass:NSString.class];
    [[[mock stub] andReturn:@"mocktest"] lowercaseString];

    NSString *returnValue = [mock lowercaseString];
    GHAssertEqualObjects(@"mocktest", returnValue, 
        @"Should have returned the expected string.");
}

- (void)testOCMockFail {
    id mock = [OCMockObject mockForClass:NSString.class];
    [[[mock stub] andReturn:@"mocktest"] lowercaseString];

    NSString *returnValue = [mock lowercaseString];
    GHAssertEqualObjects(@"thisIsTheWrongValueToCheck", 
        returnValue, @"Should have returned the expected string.");
}

@end

And finally, run the MyProjTests target in the simulator and it should look like this:

Sample test for GHUnit and OCMock

The tests we added that use OCMock merely demonstrate we have the project configured correctly. They do not show the usefulness of mock objects or the OCMock framework.

Mock objects are useful in testing that a class interacts with other objects properly, without the need to configure a large object hierarchy, and in some cases before a class is even implemented.

Where To Go From Here?

Here is the sample project with all of the code from the above tutorial.

Congratulations, now you know how to integrate OCUnit, GHUnit, and OCMock into your Xcode project!

However, this tutorial did not touch on how to make good use of unit tests in your iOS project, but I will soon be releasing a tutorial series on Test Driven Development for iOS, so stay tuned!

In the meantime, if you would like more information about GHUnit or OCMock, one of these links might help.

If you have any questions, comments, or suggestions, please join in the forum discussion below!