Getting OCMock to work
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!
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.
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.
Yeah, helped. I tried to use @”className” instead of [className class] as mockForClass: