1

How can I unit test this hitTest override?

- (UIView*) hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView* hitView = [super hitTest:point withEvent:event];
    // Do something based on hitView's properties
}

The problem I'm facing is that UIEvent does not have a public constructor, and thus I can't create an UIEvent to produce different results on [super hitTest:point withEvent:event].

Alternatively I could create a mock UIEvent, but that would imply knowing what [super hitTest:point withEvent:event] does with it, which I don't, and even if I did, it might change.

Another option would be to swizzle [super hitTest:point withEvent:event] (with OCMock) but I don't know if it's possible to swizzle just the superclass implementation.

hpique
  • 119,096
  • 131
  • 338
  • 476

1 Answers1

2

You could wrap the call to super and use a partial mock.

In the class under test, create something like:

-(UIView *)checkHit:(CGPoint)point withEvent:(UIEvent *)event {
    return [super hitTest:point withEvent:event];
}

Then in your test class:

CGPoint testPoint = CGPointMake(1,2);
id mockHitView = [OCMockObject mockForClass:[UIView class]];
id mockSomething = [OCMockObject partialMockForObject:realObject];
[[[mockSomething stub] andReturn:mockHitView] checkHit:testPoint withEvent:[OCMArg any]];

[realObject hitTest:testPoint withEvent:nil];
Christopher Pickslay
  • 17,523
  • 6
  • 79
  • 92
  • +1 While this would work, it forces me to create a method that makes the code slightly more confusing. I'm not against adding code for testing purposes as long as it makes the code clearer (fortunately, it usually does). – hpique Dec 19 '11 at 22:51