dimanche 3 avril 2016

UnitTest a Service with AFNetworking 3.x

I do want to test my Service that calls a method that uses AFNetworking 3.x.

Service:

+ (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;
    });
}

Client:

#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);
        }];

    }];
}

UnitTest:

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();
        });

    });

But I always got an error on thenBlock, an EXC_BAD_ACCESS.

Aucun commentaire:

Enregistrer un commentaire