0

I have a method that takes a response block and an error block, I write unit test by giving it valid data and invalid data so it will call response block and error block respectively, but with GHUnit and OCMock, how do I test if the correct block is called?

I was thinking:

for valid data: response { GHAssertTrue(YES, @""); } error { GHAssertTrue(NO, @"Valid data should not call error block"); }

and vice-versa for invalid data.

Is what I did correct?

hzxu
  • 5,753
  • 11
  • 60
  • 95

2 Answers2

0

Here's what I'd do instead:

  • Add a property to the test class to indicate which block was called
  • Have each block set that property to a different value
  • Invoke
  • Check the value of the property
Jon Reid
  • 20,545
  • 2
  • 64
  • 95
0

The problem with putting your assertions in the blocks is that you wouldn't know if neither block were called. This is what we do:

__block BOOL done = NO;
[classUnderTest doSomethingWithResultBlock:^(BOOL success) {
    done = YES;
} errorBlock:^(BOOL success) {
    // should not be called
    expect(NO).to.beTruthy();
}];
while (!done) [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];

The drawback is that if the success block is never called, the tests will hang in the while loop. You could avoid that by adding a timeout:

NSDate *startTime = [NSDate date];
__block BOOL done = NO;
[classUnderTest doSomethingWithResultBlock:^(BOOL success) {
    done = YES;
} errorBlock:^(BOOL success) {
    // should not be called
    expect(NO).to.beTruthy();
}];
while (!done && [startTime timeIntervalSinceNow] > -30) [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];
// make sure it didn't time out
expect(done).to.beTruthy();
Christopher Pickslay
  • 17,523
  • 6
  • 79
  • 92
  • [expecta](https://github.com/petejkim/expecta) is the assertion library we use in our tests. That statement is equivalent to `GHAssertTrue(done, @"Check for result block should not have timed out.");` – Christopher Pickslay Nov 02 '12 at 19:17