1
votes

I am facing some hard time in mocking a block inside one of my methods which i want to test.

Below is more or less how my code looks like

- (void) startFetching:(MyParameter *) parameter
{
    self.fetcher = [[MyFetcher alloc] initWithContext:xxxx andObserver:nil];
    self.fetcher.parameters = @[parameter];
    [self.fetcher startWithCompleteionBlock:^(id<MyOperation>  _Nonnull operation) {
        if(operation.errors.count > 0) {
            [self.delegate failedWithError:operation.errors.firstObject];
        } else{
            FetcherResponse *response = [MyFetcherResponse cast:operation];
            NSArray *array =  response.responseArray;
           if(array.count == 1) {
                [self.delegate completedWithSuccess:array.firstObject];
            }
        }
    }];
}

Now i have a test method like testStartFetching and i want to test this method. i don't understand how i can stub this part [self.fetcher startWithCompleteionBlock:^(id<MyOperation> _Nonnull operation) inside my method so that, in success case it return proper array and in failure case it return errors and if i stub it for with errors then failedWithError:operation is called and completedWithSuccess is called otherwise.

I am using OCMock framework in objective c and i am new to unit testing. Any help will be highly appreciated.

1

1 Answers

1
votes

I stub method with completion block which returns operation (with errors). Then I verify that calls delegate's method - failedWithError with right parameter (error).

   id<MyOperation> operation = [[MyClassOperaion alloc] init];
    NSError *error = [NSError new];
    operation.errors = @[error];

    OCMStub([self.fetcher startWithCompleteionBlock:([OCMArg checkWithBlock:^BOOL(void(^passedBlock)(id<MyOperation>  _Nonnull operation)) {
        passedBlock(operation);
        return YES;
    }])]);

    OCMVerify([self.delegate failedWithError:error]);