如何对AFNetworking请求进行单元测试

时间:2013-09-30 13:19:01

标签: ios unit-testing afnetworking ocmock

我正在GET请求使用JSON检索AFNetworking数据,如下面的代码所示:

        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,但无法弄清楚如何管理它。

1 个答案:

答案 0 :(得分:12)

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

其次,您正在创建请求,然后是AFHTTPRequestOperation,然后您将其排队。这很好,但你可以使用AFHTTPClient方法得到相同的getPath:参数:success:failure:。

我没有使用建议的HTTP存根工具(Nocilla)的经验,但我发现它基于NSURLProtocol。我知道有些人使用这种方法,但我更喜欢创建自己的存根响应对象并模拟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版本已经发布,因此如果它满足您的要求,请考虑使用它。