OCMock Return a struct

Why do I always seem to be the one person with these difficult problems? First, it was like murder to run OCMock under the iPhone SDK. Frameworks, dependencies, debugging, chaos! Then it was the whole tests fail but the build passes thing. I seriously believe I must the only person on the planet who’s trying to do REAL agile development on an iPhone project. Getting to the point, if you ever try using OCMock and you’ve run into the issue with struct return values then the following is for you.

The other day I find myself trying to mock some stuff around CoreLocation and I hit a snag! I can’t return a CLLocationCoordinate2D type from a mock! Try it yourself and you’ll see what I mean. I tried using the OCMOCK_VALUE macro to no avail. I posted on various forums for help and received no valuable replies. The true answer is a slight variation of another similar blog post. Rather than go into an in depth explanation I’ll post my fix here. I put the following in the header/impl of a SenTestCase subclass and all is good for any object that subclasses my subclass.

@interface OCMockRecorder (ExtraMethods)
- (id) andReturnBoolean:(BOOL)aValue;
- (id) andReturnStruct:(void*)aValue objCType:(const char *)type;

@implementation OCMockRecorder (ExtraMethods)

- (id) andReturnBoolean:(BOOL)aValue {
    NSValue *wrappedValue = nil;
    wrappedValue = [NSValue valueWithBytes:&aValue
    return [self andReturnValue:wrappedValue];

- (id) andReturnStruct:(void*)aValue objCType:(const char *)type{
    NSValue *wrappedValue = nil;
    wrappedValue = [NSValue valueWithBytes:aValue
    return [self andReturnValue:wrappedValue];


2 thoughts on “OCMock Return a struct

  1. What are you using for that code box? Its been causing a lot of problems for me.

    I am trying to copy and paste the code example, but it has all that “<img src= …” stuff in it and the view plain suffers the same problem. The copy to clipboard function doesn’t seem to work, perhaps thats a mac specific problem? But I assume mac users are your target audience. I would look at changing up how you are displaying your code to make things easier for your readers.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s