【发布时间】:2009-06-09 14:17:45
【问题描述】:
对于我正在开发的游戏,我有几个模型类会在它们的状态发生变化时触发通知。然后,视图订阅这些通知并对它们做出反应。
我正在使用 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 中添加一个设置器并注入我自己的NSNotificationCenter,但我正在寻找一种更快的方法来做到这一点(也许是一些关于如何动态替换NSNotificationCenter 的技巧)。
【问题讨论】:
-
+1 用于单元测试通知的巧妙方式!
标签: iphone objective-c unit-testing