Skip to content

Getting OCMock to work

2009 February 19
by Nayan Hajratwala

I started using OCMock yesterday, and was quickly hit by a problem when trying to stub out return values.

My test method was (sorry for the lack of highlighting – the plugin i’m using doesn’t support Objective-C)

- (void)testReturnsStubbedReturnValue
{
	id mock = [OCMockObject mockForClass:[NSString class]];
	[[[mock stub] andReturn:@"megamock"] lowercaseString];
	id returnValue = [mock lowercaseString];
	
	STAssertEqualObjects(@"megamock", returnValue, @"Should have returned stubbed value.");
}

However, when running it, I would get the error:

  warning no '-stub' method found
  warning no '-andReturn' method found

After scrolling through all the OCMock test code, I finally was able to get it work by adding:

  #import <OCMock/OCMock.h>

That’s where the methods are defined, but not being an Obj-C guru, I don’t fully understand how the code knows it’s actually using the OCMock class, etc.

Anyway, it appears that the minimal code needed to get an OCMock test running is (i wish this was on their web site!):

In OCMockSampleTest2.h:

#import <SenTestingKit/SenTestingKit.h>

@interface OCMockSampleTest2 : SenTestCase {
}

@end

In OCMockSampleTest2.m:

#import "OCMockSampleTest2.h"
#import <OCMock/OCMock.h>
#import <OCMock/OCMConstraint.h>

@implementation OCMockSampleTest2

- (void)testReturnsStubbedReturnValue
{
	id mock = [OCMockObject mockForClass:[NSString class]];
	[[[mock stub] andReturn:@"megamock"] lowercaseString];
	id returnValue = [mock lowercaseString];
	
	STAssertEqualObjects(@"megamock", returnValue, @"Should have returned stubbed value.");
}

@end

I hope this helps someone!