如何测试AFNetworking

时间:2013-10-12 16:19:55

标签: ios afnetworking kiwi nocilla ohhttpstubs

* 编辑 - 我最初想使用AFNetworking测试Nocilla,但最终使用OHHTTPStubs来完成这项工作。我已使用OHHTTPStubs *

回答了下面的原始问题

原始问题:

我想测试我们的应用程序的APIClient - 下面详细介绍了需要测试的方法之一。所以我需要模仿来自HTTPRequestOperationWithRequest:的{​​{1}}来电。 AFNetworking似乎是执行此操作的选项(比Nocilla更合适)。 我查看了the github page处理OCMockNocilla的内容,但我不确定如何将其应用于我的问题 - 语法不是很熟悉。

  • 所以我想知道是否有人可以给我一个关于如何在这种情况下使用AFNetworking的提示?
  • 此外,必须使用Nocilla Kiwi吗?

提前致谢:)

Nocilla

1 个答案:

答案 0 :(得分: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;

}
相关问题