* 编辑 - 我最初想使用AFNetworking
测试Nocilla
,但最终使用OHHTTPStubs
来完成这项工作。我已使用OHHTTPStubs
*
原始问题:
我想测试我们的应用程序的APIClient - 下面详细介绍了需要测试的方法之一。所以我需要模仿来自HTTPRequestOperationWithRequest:
的{{1}}来电。 AFNetworking
似乎是执行此操作的选项(比Nocilla
更合适)。
我查看了the github page处理OCMock
和Nocilla
的内容,但我不确定如何将其应用于我的问题 - 语法不是很熟悉。
AFNetworking
的提示?Nocilla
Kiwi
吗? 提前致谢:)
Nocilla
答案 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;
}