HannahCarney
HannahCarney

Reputation: 3631

Testing Reactive Cocoa HTTP request with Objective-C

In DataManager.m I have my function that returns a response object if successful:

+(RACSignal *)signalVerifyPin:(NSString *)pin
{
    NSString *urlBase = [DataService buildUrl:@"checkpin?pin="];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    return [RACSignal createSignal:^RACDisposable *(id subscriber) {


        [manager GET: [NSString stringWithFormat:@"%@%@", urlBase, pin]  parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"JSON: %@", responseObject);

            NSDictionary *response = [responseObject objectForKey:@"response"];

            [subscriber sendNext:responseObject];
            [subscriber sendCompleted];


        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error: %@", error);
            [subscriber sendError:error];
        }];

        return nil;
    }];
}

I would love to test this piece of code, but I can't find any information on how to do so.

Thanks so much!

Upvotes: 1

Views: 140

Answers (1)

Dan Atherton
Dan Atherton

Reputation: 161

I think you are asking how to test asynchronous functions. For this you can use XCTestExpectation.

for example

- (void)testCheckPin
{
    XCTestExpectation *expectation =
        [self expectationWithDescription:@"Check Pin"];

    [[SomeClass signalVerifyPin:@"somePin"] subscribeNext:^(id x){
            XCTAssert(assertSomething);
        } error:^(NSError *){
           XCTAssert(assertSomething);
           [expectation fulfill];

        } completed:^{
          XCTAssert(assertSomething);
          [expectation fulfill];
    }];


    [self waitForExpectationsWithTimeout:5.0 handler:^(NSError *error) {
        if (error) {
            NSLog(@"Timeout Error: %@", error);
        }
    }];
}

Hope this helps :)

Upvotes: 1

Related Questions