如何使用AFNetworking对api呼叫进行单元测试

squ*_*rog 4 ios afnetworking kiwi

我有一个我正在处理的iOS应用程序,它连接到第三方Web服务.我有大约50个不同的调用,并希望使用Kiwi编写单元测试,但我不知道从哪里开始.

由于我不负责API,我需要使用正确的GET或POST方法检查我的调用是否指向正确的URL.

有没有办法正确测试?

下面是我的一个电话的例子:

+ (void)listsForUser:(NSString *)username
            response:(void (^)(NSArray *lists))completion
{
    NSString *path = [NSString stringWithFormat:@"user/list.json/%@/%@", TRAKT_API_KEY, username];
    [TNTraktAPIManager requestWithMethod:GET
                                    path:path
                              parameters:nil
                                callback:^(id response) {
                                    completion(response);
                                }];
}
Run Code Online (Sandbox Code Playgroud)

其中调用以下辅助方法

+ (void)requestWithMethod:(HTTPMethod)method
                     path:(NSString *)path
               parameters:(NSDictionary *)params
                 callback:(void (^)(id response))completion
{
    NSString *methodString = @"POST";
    if (method == GET) {
        methodString = @"GET";
    }


    // Setup request
    NSURLRequest *request = [[TraktAPIClient sharedClient] requestWithMethod:methodString
                                                                        path:path
                                                                  parameters:params];

    // Setup operation
    AFJSONRequestOperation *operation =
    [AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                                    success:^(NSURLRequest *request,
                                                              NSHTTPURLResponse *response,
                                                              id JSON) {
                                                        id jsonResults = JSON;
                                                        completion(jsonResults);

                                                    } failure:^(NSURLRequest *request,
                                                                NSHTTPURLResponse *response,
                                                                NSError *error,
                                                                id JSON) {

                                                        id jsonResults = JSON;
                                                        completion(jsonResults);
                                                        NSLog(@"%s: error: %@", __PRETTY_FUNCTION__, error);

                                                    }];
    // TODO: Queue operations
    [operation start];

}
Run Code Online (Sandbox Code Playgroud)

Tim*_*imD 5

如果您shouldEventually在帮助程序类上设置了一个期望并使用该receive:(SEL)withArguments:(id)...表单,那么您可以检查收到的参数是否是您期望的.

值得了解的两个问题是在打电话之前设定期望值; 并且使用shouldEventually表单而不是should使测试延迟足够长的时间来进行调用.

  • 这是一个容易犯的错误.如果我每次完成它都有$ currencyUnit $ ...! (2认同)