iOS   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – 如何单元测试AFNetworking请求大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在通过AFNetworking作为GET请求来检索 JSON数据,如下所示:
NSURL *url = [NSURL URLWithString:K_THINKERBELL_SERVER_URL];
    AFhttpClient *httpClient = [[AFhttpClient alloc] initWithBaseURL:url];
    Account *ac = [[Account alloc]init];
    NSMutableURLrequest *request = [httpClient requestWithMethod:@"GET" path:[NSString StringWithFormat:@"/user/%@/event/%@",ac.uid,eventID]  parameters:nil];

    AFhttprequestOperation *operation = [httpClient httprequestOperationWithrequest:request
                                                                            success:^(AFhttprequestOperation *operation,id responSEObject) {
                                                                                NSError *error = nil;
                                                                                NSDictionary *JSON = [NSJSONserialization JSONObjectWithData:responSEObject options:NSJSONReadingAllowFragments error:&error];
                                                                                if (error) {
                                                                                }

                                                                                [self.delegate NextMeeTingFound:[[MeeTing alloc]init] meeTingData:JSON];

                                                                            }
                                                                            failure:^(AFhttprequestOperation *operation,NSError *error){
                                                                            }];
    [httpClient enqueuehttprequestOperation:operation];

事情是我想基于这个数据创建一个单元测试,但我不想让测试实际上会提出请求.我希望预定义的结构将作为响应返回.我是一个新的单元测试,并戳了一点OCmock,但不知道如何管理这个.

解决方法

几个事情要评论你的问题.
首先,您的代码很难测试,因为它直接创建了AFhttpClient.我不知道是不是因为它只是一个样本,但是你应该注入它(参见下面的示例).

其次,您正在创建请求,然后是AFhttprequestOperation,然后将其排入队列.这很好,但您可以使用AFhttpClient方法getPath获取相同的参数:参数:success:failure:.

我没有那个建议的http stubbing工具(Nocilla)的经验,但我看到它是基于NSURLProtocol.我知道有些人使用这种方法,但我更喜欢创建自己的stubbed响应对象,并模仿http客户端,就像在下面的代码中看到的那样.

Retriever是我们要测试我们注入AFhttpClient的类别.
请注意,我直接传递用户和事件ID,因为我想保持简单易用的测试.然后在其他地方你可以将accout uid值传递给这个方法等等…
文件看起来与此类似:

#import <Foundation/Foundation.h>

@class AFhttpClient;
@protocol RetrieverDelegate;

@interface Retriever : NSObject

- (id)initWithhttpClient:(AFhttpClient *)httpClient;

@property (readonly,strong,nonatomiC) AFhttpClient *httpClient;

@property (weak,nonatomiC) id<RetrieverDelegate> delegate;

- (void) retrieveEventWithUserId:(NSString *)userId eventId:(NSString *)eventId;

@end


@protocol RetrieverDelegate <NSObject>

- (void) retriever:(Retriever *)retriever didFindEvenData:(NSDictionary *)eventData;

@end

执行文件

#import "Retriever.h"
#import <AFNetworking/AFNetworking.h>

@implementation Retriever

- (id)initWithhttpClient:(AFhttpClient *)httpClient
{
    NSParameterAssert(httpClient != nil);

    self = [super init];
    if (self)
    {
        _httpClient = httpClient;
    }
    return self;
}

- (void)retrieveEventWithUserId:(NSString *)userId eventId:(NSString *)eventId
{
    NSString *path = [NSString StringWithFormat:@"/user/%@/event/%@",userId,eventId];

    [_httpClient getPath:path
              parameters:nil
                 success:^(AFhttprequestOperation *operation,id responSEObject)
    {
        NSDictionary *eventData = [NSJSONserialization JSONObjectWithData:responSEObject options:0 error:NULL];
        if (eventData != nil)
        {
            [self.delegate retriever:self didFindEventData:eventData];
        }
    }
                 failure:nil];
}

@end

和测试:

#import <XCTest/XCTest.h>
#import "Retriever.h"

// Collaborators
#import <AFNetworking/AFNetworking.h>

// Test support
#import <OCmock/OCmock.h>

@interface RetrieverTests : XCTESTCase

@end

@implementation RetrieverTests

- (void)setUp
{
    [super setUp];
    // Put setup code here; it will be run once,before the first test case.
}

- (void)tearDown
{
    // Put teardown code here; it will be run once,after the last test case.
    [super tearDown];
}

- (void) test__retrieveEventWithUserIdEventId__when_the_request_and_the_JSON_parsing_succeed__it_calls_didFindEventData
{
    // CreaTing the mocks and the retriever can be placed in the setUp method.
    id mockhttpClient = [OCmockObject mockForClass:[AFhttpClient class]];

    Retriever *retriever = [[Retriever alloc] initWithhttpClient:mockhttpClient];

    id mockDelegate = [OCmockObject mockForProtocol:@protocol(RetrieverDelegatE)];
    retriever.delegate = mockDelegate;

    [[mockhttpClient expect] getPath:@"/user/testuserId/event/testEventId"
                          parameters:nil
                             success:[OCMArg checkWithBlock:^BOOL(void (^successBlock)(AFhttprequestOperation *,id))
    {
        // Here we capture the success block and execute it with a stubbed response.
        NSString *jsonString = @"{\"some valid JSON\": \"some value\"}";
        NSData *responSEObject = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

        [[mockDelegate expect] retriever:retriever didFindEventData:@{@"some valid JSON": @"some value"}];

        successBlock(nil,responSEObject);

        [mockDelegate verify];

        return YES;
    }]
                             failure:OCmock_ANY];

    // Method to test
    [retriever retrieveEventWithUserId:@"testuserId" eventId:@"testEventId"];

    [mockhttpClient verify];
}

@end

最后要注意的是,AFNetworking 2.0版本被发布,所以虑使用它,如果它涵盖了您的要求.

大佬总结

以上是大佬教程为你收集整理的ios – 如何单元测试AFNetworking请求全部内容,希望文章能够帮你解决ios – 如何单元测试AFNetworking请求所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。