Objective c OCMock测试通过的块是否正确执行

Objective c OCMock测试通过的块是否正确执行,objective-c,unit-testing,ocmock,Objective C,Unit Testing,Ocmock,如何验证传递的块是否正确执行 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { [self updatePostalCode:newLocation withHandler:^(NSArray *placemarks, NSError *error) {

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

- (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的设置是否正确,但我不知道如何使用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]);

从类上的方法返回处理程序块,包括可测试性

- (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");
}

感谢这篇文章完美地解释了它背后的智慧,但我不理解
[myClass handleLocationUpdate]([NSArray arrayWithObject:mockPlacemark],无)和从不看
expect()。到…
我可以参考这些吗?我把我的代码复制到了你的问题中,我明白了吗?如果你定义了所列的方法,那么
[myClass handleLocationUpdate]
返回块。您正在将块作为函数执行,并传入包含模拟的placemarks数组。
expect()
来自Pete Kim的优秀matcher框架。我们在所有项目中都使用它。松耦合“self”的一个好例子需要在返回块的方法中很弱。