I have a function (internally uses ASIHTTPRequest) which calls a block with the result:
[Http get:@"http://api.geonames.org/postalCodeLookupJSON"
params:params cacheMins:0 complete:^(NSDictionary *response, BOOL success) {
STAssertTrue(success, @"JSON retrieved OK");
STFail(@"blah");
}];
I want to test the above, but it seems the test doesn't get called.
How can i ensure that the test waits till the block is called?
-edit-
Of course i don't recommend to do this in the main app in the gui thread, i开发者_如何转开发n this particular situation it is only for a unit test.
Found a solution:
Wait for code to finish execution
Eg:
__block int done=0;
[Http get:@"http://api.geonames.org/postalCodeLookupJSON"
params:params cacheMins:0 complete:^(NSDictionary *response, BOOL success) {
STAssertTrue(success, @"JSON retrieved OK");
NSArray *postalcodes = [response objectForKey:@"postalcodes"];
NSDictionary *first = [postalcodes objectAtIndex:0];
NSString *adminName1 = [first objectForKey:@"adminName1"];
STAssertTrue([adminName1 isEqualToString:@"New South Wales"], @"NSW");
done=1;
}];
// https://stackoverflow.com/questions/3615939/wait-for-code-to-finish-execution
while (!done) {
// This executes another run loop.
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
// Sleep 1/100th sec
usleep(10000);
}
Not sure where I found this, but there's a better way that doesn't use sleeps:
while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true) && !placeMarkUpdated){};
here it is in context, testing a reverse geocoding request:
__block BOOL placeMarkUpdated = NO;
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
if (placeMarkUpdated == NO) {
placeMarkUpdated = YES;
CLPlacemark *placemark = [placemarks objectAtIndex:0];
address = [Address addressFromPlacemark:placemark];
}
}];
while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true) && !placeMarkUpdated){};
Sleeps suck cause they slow down the build (I know 5s doesn't sound bad, but consider the old story: guy goes to doctor cause his knees hurt from running, Doctor says 'get up on the table' and taps his knee and says 'does that hurt?' guy says 'no,' doctor: 'it would if I did it 10K times...'
精彩评论