如何模拟AFHTTPClient类和测试方法getPath:参数:成功:失败:?

时间:2013-12-01 12:26:27

标签: ios objective-c mocking afnetworking ocmock

我是AFNetworking框架的新手。我已经向服务器实现了简单的GET请求。

@implementation MyClass
…

- (void)signInWithUsername:(NSString *)username andPassword:(NSString *)password withBlock:(SignInBlock)block {
[client getPath:@"test.json" parameters:Nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    block(YES, [responseObject objectForKey:@"access_token"]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    block(NO, nil);
}];
}

块声明:

typedef void (^SignInBlock)(BOOL success, NSString *token);

我不知道如何正确地模拟这个AFHTTPClient对象来检查参数(SignInBlock)中的块是否已被调用以及使用了什么参数。我怎么能正确地做到这一点?

提前谢谢。

2 个答案:

答案 0 :(得分:2)

我已经完成了。

- (void)testTokenInBlockShouldBeNotNil {

id mockClient = [OCMockObject mockForClass:[AFHTTPClient class]];

[[[mockClient expect] andDo:^(NSInvocation *invocation) {

    void (^successBlock)(AFHTTPRequestOperation *operation, id responseObject) = nil;

    [invocation getArgument:&successBlock atIndex:4];

    successBlock(nil, @{@"access_token" : @"this_is_a_token"});

}] getPath:[OCMArg any] parameters:[OCMArg any] success:[OCMArg any] failure:[OCMArg any]] ;

RKObjectManager *manager = [[RKObjectManager alloc] init];
manager.HTTPClient = mockClient;

TokenBlock block = ^(NSString *token) {
    XCTAssertNotNil(token, @"");
};

CTFAPIConnection *connection = [[CTFAPIConnection alloc] initWithManager:manager];
_accounts = [[CTFAPIAccounts alloc] initWithConnection:connection];
id mockAccounts = [OCMockObject partialMockForObject:_accounts];
[mockAccounts signInWithUsername:[OCMArg any] andPassword:[OCMArg any] withBlock:block];
}

答案 1 :(得分:1)

在你的情况下你根本不需要模拟,只是断言正确的值被发送到你的块:

考虑Foo

- (void)signInWithUsername:(NSString *)username andPassword:(NSString *)password withBlock:(SignInBlock)block
{
    if ([username isEqualToString:@"Ben"])
    {
        block(YES, @"bentoken");
    }
    else
    {
        block(NO, nil);
    }
}

测试是:

- (void)testSignInWithUsername
{
    SignInBlock testYes = (SignInBlock)^(BOOL *success, NSString *token)
    {
        STAssertTrue(success, @"Expected Ben to be true");
        STAssertEqualObjects(token, @"bentoken", @"Expected the ben token");
    };
    Foo *foo = [Foo new];
    [foo signInWithUsername:@"Ben" andPassword:@"Whatever" withBlock:testYes];
}