如何模拟AFHTTPClient类和测试方法getPath:parameters:success:failure:



我是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)的块以及使用了什么参数。我怎样才能正确地做到这一点?

提前谢谢。

我已经完成了。

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

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

考虑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];
}

相关内容

  • 没有找到相关文章

最新更新