How to test if a block gets invoked

940 Views Asked by At

I have a unit test for a method that should call either a completion block or a failed block. Now I know for every case which one should be called so I use STFail in the block that should not be invoked.

How can I now test that the block that should be invoked is really invoked?

This is my setup:

NSString *parameter = @"foo";
[controller doSomethingWithParameter:parameter withcompletionBlock: 
^(NSString *result)
{
    // This block should be invoked
    // Check if the result is correct
    STAssertEquals(result, kSomeOKConstant, @"Result shout be 'kSomeOKConstant'");
} failedBlock:
^(NSString *errorMessage) {
    STFail(@"No error should happen with parameter '%@'",parameter);
}];
1

There are 1 best solutions below

7
On BEST ANSWER

You need to add block variables, and set them from inside your blocks:

BOOL __block successBlockInvoked = NO;
BOOL __block failureBlockInvoked = NO;
NSString *parameter = @"foo";
[controller doSomethingWithParameter:parameter withcompletionBlock: 
^(NSString *result) {
     successBlockInvoked = YES;
     STAssertEquals(result, kSomeOKConstant, @"Result shout be 'kSomeOKConstant'");
} failedBlock:
^(NSString *errorMessage) {
    failureBlockInvoked = YES;
    STFail(@"No error should happen with parameter '%@'",parameter);
}];

At this point you can make assertions about the values of successBlockInvoked and failureBlockInvoked: if the expected one is not set, your test has failed.