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!

View Comments leave one →
  1. July 6, 2009

    In OCMockSampleTest2.m you don’t need to #import becuase that is already imported by OCMock.h.

    When dealing with Objective-C frameworks you generally only need to import the top level header file. I say generally, because some frameworks (such as the AddressBook Framework) split functionality a bit.

  2. drx777 permalink
    April 14, 2010

    Yeah, helped. I tried to use @”className” instead of [className class] as mockForClass:

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS

blog comments powered by Disqus