objective-cunit-testingkiwi

How do I perform a kiwi unit test, inside a JSON callback?


I am trying to run a kiwi test, it doesn't evaluate the kiwi statement on the inner block. But it will evaluate any test statements outside the block. What do I do? :

- (void) jsonTest:(void (^)(NSDictionary *model))jsonData{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://api.somesite.com" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        if(jsonData){
            jsonData((NSDictionary *)responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        jsonData(nil);
    }];
}

describe(@"Networking", ^{
    it(@"Get Sample JSON", ^{


    [[NetworkingUtil alloc] jsonTest:^(NSDictionary *model){

        NSString * result = [model objectForKey:@"Host"];
        NSLog(@"result :: %@", result);

        [[result should] equal: @"host.value.name"];            
    }];

    //kiwi evaluates this test statement though...
    [[theValue(41) should] equal:theValue(42)];
}];

Solution

  • You need to use KWCaptureSpy.

    NetworkingUtil *jsonT = [NetworkingUtil alloc];
    // We tell the spy what argument to capture.
    KWCaptureSpy *spy = [jsonT captureArgument:@selector(jsonTest:) atIndex:0];
    
    [jsonT jsonTest:^(NSDictionary *model){
    
        NSString * result = [model objectForKey:@"Host"];
        NSLog(@"result :: %@", result);
    
        [[result should] equal: @"host.value.name"];            
    }];
    
    void (^myTestBlock)(NSDictionary *model) = spy.argument;
    
    myTestBlock(dictionary);
    

    You do have to create a dictionary that you will pass for a test. Its the same for any block even the one inside the jsonTest: method.

    When it comes to Kiwi and testing blocks in blocks it gets a bit crazy but the concept is the same. You capture the method that has the completion block you capture the argument that is the block you wish to test and pass it an object it requires.