UnitTest与AFNetworking 3.x的服务

时间:2016-04-03 14:31:18

标签: ios objective-c unit-testing ocmock afnetworking-3

我确实想测试调用使用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。

0 个答案:

没有答案