對於比賽我發展,我有觸發通知時,他們的狀態發生變化的幾個模型類。然後,該視圖訂閱這些通知,並可以對它們做出反應。的OCUnit測試NSNotification交付
我做與的OCUnit模型我的單元測試,並希望斷言預期的通知被張貼。對於這一點,我在做這樣的事情:
- (void)testSomething {
[[NSNotificationCenter defaultCenter] addObserver:notifications selector:@selector(addObject:) name:kNotificationMoved object:board];
Board *board = [[Board alloc] init];
Tile *tile = [Tile newTile];
[board addTile:tile];
[board move:tile];
STAssertEquals((NSUInteger)1, [notifications count], nil);
// Assert the contents of the userInfo as well here
[board release];
}
的想法是,將NSNotificationCenter
通過調用其addObject:
方法通知添加到NSMutableArray
。
然而,當我運行它時,我發現addObject:
正在發送到某個其他對象(而不是我的NSMutableArray
),導致OCUnit停止工作。但是,如果我註釋掉某些代碼(例如release
調用,或添加新的單元測試),則所有事情都按預期開始工作。
我假設這有鄰與時機的問題,或NSNotificationCenter
依靠以某種方式運行循環。
有沒有任何建議來測試這個?我知道我可以在Board
中添加一個setter,並注入我自己的NSNotificationCenter
,但我正在尋找一種更快的方法來做到這一點(也許有一些關於如何動態替換NSNotificationCenter
的技巧)。
+1爲單元測試通知的聰明方式! – 2011-07-21 13:53:43