测试传递块的OCMock正确执行

时间:2012-06-25 12:41:15

标签: objective-c unit-testing ocmock

如何验证传递块是否正确执行?

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    [self updatePostalCode:newLocation withHandler:^(NSArray *placemarks, NSError *error) {
    // code that want to test
        CLPlacemark *placemark = [placemarks objectAtIndex:0];
        self.postalCode = [placemark postalCode];
        _geocodePending = NO;
    }];

    ....
}

我想知道postalCode,_geocodePending设置正确,但我无法弄清楚如何使用OCMock。

添加了代码

id mockSelf = [OCMockObject partialMockForObject:_location];

    id mockPlacemart = (id)[OCMockObject mockForClass:[CLPlacemark class]];

    [[[mockPlacemart stub] andReturn:@"10170"] postalCode];

    [mockSelf setGeocodePending:YES];
    [mockSelf setPostalCode:@"00000"];

    [self.location handleLocationUpdate]([NSArray arrayWithObject:mockPlacemart], nil);

    STAssertFalse([mockSelf geocodePending], @"geocodePending should be FALSE");
    STAssertTrue([[mockSelf postalCode] isEqualToString:@"10170"], @"10170", @"postal is expected to be 10170 but was %@" , [mockSelf postalCode]);

1 个答案:

答案 0 :(得分:6)

从您班级的方法返回您的处理程序块。 There are a few good reasons to do this,包括可测试性。

- (void (^)(NSArray *, NSError *))handleLocationUpdate {
    __weak Foo *weakself = self;
    return ^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark = [placemarks objectAtIndex:0];
        weakself.postalCode = [placemark postalCode];
        weakself.geocodePending = NO;
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    [self updatePostalCode:newLocation withHandler:[self handleLocationUpdate]];

    ....
}

然后,在你的测试中:

-(void)testLocationUpdates {
    id mockPlacemark = [OCMockObject mockForClass:[CLPlacemark class]];
    [[[mockPlacemark stub] andReturn:@"99999"] postalCode];

    myClass.geocodePending = YES;
    myClass.postalCode = @"00000";

    [myClass handleLocationUpdate]([NSArray arrayWithObject:mockPlacemark], nil);

    expect(myClass.geocodePending).toBeFalsy;
    expect(myClass.postalCode).toEqual(@"99999");
}