有没有办法确保某个类发布特定的NSNotification?
(我有一组类,我想在编译时强制执行(如果可能的话)该类发布所需的NSNotification)。
或者,如果无法做到这一点,是否有解决方法?
答案 0 :(得分:3)
从根本上讲,在编译时无法预测运行时会发生什么。您可以获得的最接近的是静态分析,但即使这样也无法预测在您自己的代码之外发生的任何事情,例如在Foundation内部。
但是,您可以使用单元测试来执行此操作,因为测试运行器实际上运行了测试代码。
如果您还没有,则需要创建测试包目标。您的目标将使用SenTestingKit来运行您创建的测试。 (在iPhone上,你还需要谷歌工具箱,呃,Mac。他们有a handy tutorial on using GTM for iPhone tests。)
您将创建一个SenTestCase子类来测试您的真实对象是否发布通知。它看起来像这样:
@interface FrobnitzerNotificationsTest: SenTestCase
{
BOOL frobnitzerDidCalibrate;
}
- (void) frobnitzerDidCalibrate:(NSNotification *)notification;
@end
@implementation FrobnitzerNotificationsTest
- (void) testFrobnitzerCalibratePostsNotification {
Frobnitzer *frobnitzer = …;
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(frobnitzerDidCalibrate:)
name:FrobnitzerDidCalibrate
object:frobnitzer];
frobnitzerDidCalibrate = NO;
//This should post a notification named FrobnitzerDidCalibrate with the receiver as the object.
[frobnitzer calibrate];
//If it did, our notification handler set frobnitzerDidCalibrate to YES (see below).
[nc removeObserver:self
name:FrobnitzerDidCalibrate
object:frobnitzer];
STAssertTrue(frobnitzerDidCalibrate, @"Frobnitzer did not post a notification when we told it to calibrate");
}
- (void) frobnitzerDidCalibrate:(NSNotification *)notification {
frobnitzerDidCalibrate = YES;
}
@end
对于要测试的每个通知,您需要一个实例变量和一个通知处理程序方法,并且需要为要测试通知的每个方法使用一种测试方法。
此外,如果使用GTM,您必须将GTMSenTestCase替换为上面的SenTestCase。