2013-10-12 18 views
3

* 编辑 - 我原本想用Nocilla测试AFNetworking,但最终使用OHHTTPStubs来完成这项工作。我已经回答了下面原来的问题,使用OHHTTPStubs *如何测试AFNetworking

原题:

我想测试我们的应用程序的APIClient - 其中需要进行测试详述如下方法之一的梗概。所以我需要模仿来自AFNetworkingHTTPRequestOperationWithRequest:电话。 Nocilla似乎是一个选择来做到这一点(比OCMock更适合)。 我已经签出the github page其中涉及NocillaAFNetworking但我不知道如何将其应用于我的问题 - 语法不是很熟悉。

  • 所以我想知道如果有人可以给我一个暗示,我可能会在这种情况下使用Nocilla
  • 此外,必须使用KiwiNocilla

感谢提前:)

-(AFHTTPRequestOperation *)getBroadcastsForChannel:(TINChannel *)channel 
            startTime:(NSDate *)date 
             limit:(NSNumber *)limit 
            pastLimit:(NSNumber *)pastLimit 
             fields:(NSArray *)fieldsArray 
             interval:(TINBroadcastsInterval)interval 
           completionBlock:(void (^)(NSArray *broadcasts, NSError *error))block { 

    // Some setup here 

    NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:params]; 

    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) { 

    NSError *error; 

    NSDictionary *responseDic = [self parseResponse:responseObject error:&error]; 

     if (error) { 
      if (block) { 
       block([NSArray array], error); 
      } 
      return; 
     } 

     // Parse the response object here 

     if (block) { 
      block([NSArray arrayWithArray:broadcastsOutput], nil); 
     } 

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 

    if (block) { 
     block([NSArray array], error); 
    } 
    }]; 

     [self enqueueHTTPRequestOperation:operation]; 

     return operation; 

} 
+0

我一直在寻找这个太的答案! – bilby91

+0

我设法通过使用不同的库 - “OHHTTPStubs”来实现这个工作。当我有机会时,我会在几个小时后发布一些示例代码。 – Octave1

+0

@ bilby91我添加了一些代码,使用'OHHTTPStubs'测试'AFNetworking'。也许这对你有一些用处。 – Octave1

回答

4

最后我用另一个库,OHHTTPStubs解决这个问题。人们可以通过AFNetworking轻松返回模拟对象,根据某些请求提供&差异响应/请求时间。 这是有据可查的here。这里还有github page。存根被删除这样的:

[OHHTTPStubs removeStub:stub]; 

下面是一些示例代码:

// A mockJSON file is loaded here 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"sampleJSON18.json"]; 
NSData* data = [NSData dataWithContentsOfFile:filePath]; 
NSError* error = nil; 
id mockJSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 

//*** stub out AFNetworkingRequestOperation and return custom NSDictionary "mockJSON", in order to see how it is handled 
id<OHHTTPStubsDescriptor> stub = nil; 
stub = [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { 
    return [[request.URL path]isEqualToString:@"/v1/epg/packages/59/broadcasts"]; // this means that any request which is equal to the above string is stubbed, return YES to stub *all* requests 
} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) { 
    // The `stubbing` procedure occurs in this block. 
    return [[OHHTTPStubsResponse responseWithJSONObject:mockJSON statusCode:200 headers:nil] requestTime:1.0f responseTime:5.0f]; // one can vary the request/responseTime here 
}]; 

stub.name = @"getChannelsWithBroadcastsForDay"; 

AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request 
                    success:^(AFHTTPRequestOperation *operation, id responseObject) 
    { 
     // The response object is now the mockJSON object, i.e. the original request is stubbed out 

     } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     // handle failure 
    } 

     }]; 

    [self enqueueHTTPRequestOperation:operation]; 
    return operation; 

} 
+3

感谢您对'OHHTTPStubs'的关注,我很高兴它对你有用:)如果你是新手,我强烈建议你直接使用最新版本'3.x'直接使用新的更清洁的API([参见ChangeLog](https://github.com/AliSoftware/OHHTTPStubs/releases))。 特别是,你可以使用'+ responseWithFileAtPath:statusCode:headers:'+'OHPathForFileInDocumentsDir(fileName)'宏([见doc here](http://cocoadocs.org/docsets/OHHTTPStubs/3.0.2/Classes/) OHHTTPStubsResponse.html#// api/name/responseWithFileAtPath:statusCode:headers :)),以避免你的代码的前6行;) – AliSoftware

+0

是的,非常感谢这是一个很好的帮助:) 我没有意识到有一个新的版本,我会研究它。 – Octave1

+1

只需要说一句:如果你想将你的存根存储在一个'static'变量中,你应该使它成为'__weak',或者在你移除存根时不要忘记将它设置回'nil',否则它会仍然保留并且不会正确清理内存。 (关于这个,请参阅README;我改进了GitHub的master分支上的文档,在标签“3.0.2”之后进行了一些提交,因此它只会包含在将来的3.0.3的doc中,但您可以直接在github上直接阅读它)。 - PS:我不确定你可以接受你自己的答案,但如果你可以,你应该这样做,告诉他人你在这里有一个工作解决方案。 – AliSoftware