我确实想测试调用使用 AFNetworking 3.x 的方法的服务。
服务:
+ (AnyPromise *)allRepositoriesfetchRepositoriesByLanguage:(NSString *)language forPage:(int)page {
return [[APIClient sharedClient] fetchRepositoriesByLanguage:language forPage:page].then(^(NSDictionary *response) {
NSValueTransformer *transformer = [MTLJSONAdapter arrayTransformerWithModelClass:[RepositoriesModel class]];
NSArray *repositories = [transformer transformedValue:response[@"items"]];
return repositories;
});
}
客户:
#pragma mark - fetchRepositoriesByLanguage
- (AnyPromise *)fetchRepositoriesByLanguage:(NSString *)language forPage:(int)page {
NSString *urlString = [NSString stringWithFormat:@"search/repositories?q=language:%@&sort=stars&page=%d", language, page];
return [self fetchWithURLString:urlString].then(^(NSDictionary *response){
return response;
});
}
- (AnyPromise *)fetchWithURLString:(NSString *)stringURL {
return [AnyPromise promiseWithAdapterBlock:^(PMKAdapter _Nonnull adapter) {
NSURL *URL = [NSURL URLWithString:stringURL];
[[APIClient sharedClient] GET:URL.absoluteString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
//NSLog(@"JSON: %@", responseObject);
NSError *error;
adapter(responseObject,error);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}];
}
单元测试:
it(@"should fetchRepositoriesByLanguage not be nil", ^{
id mockHTTPClient = [OCMockObject partialMockForObject:[APIClient sharedClient]];
[[[mockHTTPClient expect] andDo:^(NSInvocation *invocation) {
// we define the sucess block:
void (^thenBlock)(NSDictionary *response) = nil;
// Using NSInvocation, we get access to the concrete block function
// that has been passed in by the actual test
// the arguments for the actual method start with 2 (see NSInvocation doc)
[invocation getArgument:&thenBlock atIndex:1];
// now we invoke the successBlock with some "JSON"...:
thenBlock([NSDictionary dictionaryWithObjectsAndKeys:@"Bom Dia", @"greetings", nil]); //here I got error
}] fetchRepositoriesByLanguage:[OCMArg any] forPage:1];
[mockHTTPClient fetchRepositoriesByLanguage:@"Java" forPage:1].then(^(NSDictionary *response) {
expect(response).toNot.beNil();
});
});
但是我总是在 thenBlock 上遇到错误,即 EXC_BAD_ACCESS。