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:
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!