开发者

Google Toolbox For Mac : testing [NSURLConnection sendSynchronousRequest:...]

开发者 https://www.devze.com 2023-02-20 13:02 出处:网络
I\'m wondering how to test a synchronous request to assert the behavior of an API client depending on the server response.

I'm wondering how to test a synchronous request to assert the behavior of an API client depending on the server response. As it's a good practice to be independent of the server (so the test run fast and don't rely on the internet connection), I'd like to return my own response. I don't know how to do this, since the request is synchronous :

NSURL *url = [self URL];
NSData *postData = [self postData];

NSMutableURLRequest *downloadRequest = [NSMutableURLRequest requestWithURL:url];

[downloadRequest setHTTPMethod:@"POST"];
[downloadRequest setHTTPBody:postData];
[downloadRequest setTimeoutInterval:10.0];  
return downloadRequest;

NSURLResponse *response;
NSError *error = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:downloadRequest
                    returningResponse:&response
               开发者_开发技巧     error:&error];

Do you have any suggestion on how to do this ? I don't know if it's possible to override NSURLConnection for example, or if I should change my code, just for testing purposes.


I don't completely understand the first sentence of the question. I can say that you almost certainly want to make it asynchronous. A synchronous request will block the UI and if it takes too long iOS will force-quit your app. Your asynchronous request callbacks can then review the success/failure and then either call a delegate with the same response or a modified one, or post a notification that you've previously installed handlers for, again swapping the response or not as you wish.

0

精彩评论

暂无评论...
验证码 换一张
取 消