アサーションをブロックに入れる際の問題は、どちらのブロックも呼び出されていないかどうかがわからないことです。これが私たちの仕事です:
__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]];
欠点は、成功ブロックが呼び出されない場合、テストが while ループでハングすることです。タイムアウトを追加することでそれを回避できます。
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();