相关疑难解决方法(0)

如何在iOS 7.1中使用NSURLSession对HTTP请求和响应进行单元测试?

我想知道如何使用NSURLSession"单元测试"HTTP请求和响应.现在,当作为单元测试运行时,我的完成块代码不会被调用.但是,当从AppDelegate(didFinishWithLaunchingOptions)中执行相同的代码时,将调用完成块内的代码.正如在这个线程中所建议的那样,NSURLSessionDataTask dataTaskWithURL完成处理程序没有被调用,需要使用信号量和/或dispatch_group"以确保在网络请求完成之前阻塞主线程".

我的HTTP邮政编码如下所示.

@interface LoginPost : NSObject
- (void) post;
@end

@implementation LoginPost
- (void) post
{
 NSURLSessionConfiguration* conf = [NSURLSessionConfiguration defaultSessionConfiguration];
 NSURLSession* session = [NSURLSession sessionWithConfiguration:conf delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
 NSURL* url = [NSURL URLWithString:@"http://www.example.com/login"];
 NSString* params = @"username=test@xyz.com&password=test";
 NSMutableRequest* request = [NSMutableURLRequest requestWithURL:url];
 [request setHTTPMethod:@"POST"];
 [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
 NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  NSLog(@"Response:%@ %@\n", response, error); //code here never gets called in unit tests, break point here …
Run Code Online (Sandbox Code Playgroud)

objective-c ios xctest nsurlsession nsurlsessiontask

23
推荐指数
1
解决办法
1万
查看次数