Mocking gesture recognisers with OCMock

Full credit for this tip goes to my colleague, Tom Kelly.  He doesn’t have a blog at this point, so I figured I’d blog the tip for him.

You can mock gesture recognisers like any other type of object.  Its not something I’d considered before, but this means that you can unit test gesture handling functionality on your classes by calling their gesture handling methods and passing your mock gesture recogniser.

Below is an example of a mock tap gesture recogniser:

id gestureMock = [OCMockObject partialMockForObject:[[UITapGestureRecognizer new] autorelease]];
[[[gestureMock stub] andReturnValue:OCMOCK_VALUE(CGPointZero)] locationInView:[OCMArg any]];

Then, in your unit test, you call the tap handler on your class under test:

-(void)testTapBehaviour
{
    // Set up control under test here...

    // Create the mock tap gesture handler
    id gestureMock = [OCMockObject partialMockForObject:[[UITapGestureRecognizer new] autorelease]];

    // Expect:
    [[[gestureMock stub] andReturnValue:OCMOCK_VALUE(CGPointZero)] locationInView:[OCMArg any]];
    // Set up any expected behaviours on your custom class here...

    // Call the tap handler method on your custom class here...
}
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s