我正在使用AFNetworking 2.0和OHHTTPStubs编写单元测试用例,测试总是因这些错误而失败:
响应错误:无法完成操作。 (可可错误3840.)。
非常感谢!
下面是简单测试Json(User.json): { “userId”:“abc”, “email”:“ab @ pant.com”, “username”:“usera” }
和测试用例代码:
- (void)testGet
{
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
return YES; // Stub ALL requests without any condition
} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {
return [OHHTTPStubsResponse responseWithFileAtPath:OHPathForFileInBundle(@"User.json",nil)
statusCode:200 headers:@{@"Content-Type":@"application/json"}];
}];
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
AFHTTPSessionManager* requestManager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:@"http://test.com"]];
AFJSONResponseSerializer* responseSerializer = [[[AFJSONResponseSerializer alloc]init] autorelease];
responseSerializer.readingOptions = NSJSONReadingAllowFragments;
responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
responseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 2)];
requestManager.responseSerializer = responseSerializer;
AFJSONRequestSerializer* requestSerializer = [[AFJSONRequestSerializer alloc] init];
requestSerializer.writingOptions = NSJSONWritingPrettyPrinted;
[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
requestManager.requestSerializer = requestSerializer;
_done = NO;
[requestManager GET:@"stream" parameters:nil success:^(NSURLSessionDataTask * task, id JSON)
{
NSLog(@"Response data:%@", JSON);
XCTAssert(JSON != nil, @"null response");
dispatch_semaphore_signal(semaphore);
} failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
NSLog(@"Response error:%@", [error localizedDescription]);
XCTFail(@"fail to get response");
dispatch_semaphore_signal(semaphore);
}];
while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:[NSDate dateWithTimeIntervalSinceNow:10]];
}
}
答案 0 :(得分:0)
尝试使用AFHTTPResponseSerializer代替。所以基本上,替换这段代码:
AFJSONResponseSerializer* responseSerializer = [[[AFJSONResponseSerializer alloc]init] autorelease];
responseSerializer.readingOptions = NSJSONReadingAllowFragments;
responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
responseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 2)];
requestManager.responseSerializer = responseSerializer;
到这一个:
requestManager.responseSerializer = [AFHTTPResponseSerializer serializer];
因为您正在使用@" text / html"的acceptableContentType,我假设您在响应调用时不需要JSON序列化程序。所以这应该适合你的情况。