Search code examples
iphoneobjective-cocunitocmock

How to stub out the return value on a class based method using ocmock


I'm writing a test to verify location services are started when a button click occurs. This requires a very simple if statement to make sure the phone has location services available.

A working test right now looks like this

- (void)testStartUpdatingLocationInvokedWhenLocationServicesAreEnabled
{
    [[[self.locationManager stub] andReturnValue:[NSNumber numberWithBool:true]] locationServicesEnabled];
    [[self.locationManager expect] startUpdatingLocation];
    [self.sut buttonClickToFindLocation:nil];
    [self.locationManager verify];
}

The now tested implementation looks like this

- (IBAction)buttonClickToFindLocation:(id)sender
{
    if ([self.locationManager locationServicesEnabled])
    {
        [self.locationManager startUpdatingLocation];
    }
}

All good except the method was deprecated in iOS 4.0. So now I need to use the Class Method [CLLocationManager locationServicesEnabled] instead.

The problem is I can't seem to find if ocmock supports this functionality and if it doesn't how should I get around this issue for now.


Solution

  • hmmm, you could use methodExchange. Just make sure you exchange the method back to original after your done with it. It seems hacky, but I haven't found a better solution. I have done something similar for stubbing [NSDate date]

    @implementation
    
    static BOOL locationManagerExpectedResult;
    
    - (void)testStartUpdatingLocationInvokedWhenLocationServicesAreEnabled
    {
        locationManagerExpectedResult = YES;
    
        method_exchangeImplementations(
           class_getClassMethod([CLLocationManager class], @selector(locationServicesEnabled)) , 
           class_getClassMethod([self class], @selector(locationServicesEnabledMock))
        );
    
        [self.sut buttonClickToFindLocation:nil];
    }
    
    + (BOOL)locationServicesEnabledMock
    {
        return locationManagerExpectedResult;
    }
    
    @end
    

    EDIT: I thought you were verifying, but it seems like you are stubbing. Updated code