2013-12-19 51 views
2

NotificationManager.hOCMockObserver:意外通知观察

#import <Foundation/Foundation.h> 

@interface NotificationManager : NSObject 

-(void)postNotification; 

@end 

NotificationManager.m

#import "NotificationManager.h" 

@implementation NotificationManager 

-(void)postNotification 
{ 
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"Some data" forKey:@"TestData"]; 
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"TestNotification" object:nil userInfo:userInfo]]; 
} 

@end 

单元测试:

-(void)testNotification 
{ 
    id observerMock = [OCMockObject observerMock]; 

    [[NSNotificationCenter defaultCenter]addMockObserver:observerMock name:@"TestNotification" object:nil]; 

    [[observerMock expect] notificationWithName:@"TestNotification" object:[OCMArg any]]; 

    NotificationManager * nm= [[NotificationManager alloc]init]; 
    [nm postNotification]; 

    [observerMock verify]; 

    [[NSNotificationCenter defaultCenter] removeObserver:observerMock]; 
} 

我得到错误:

OCMockObserver:观察到意外通知:NSConcreteNotification 0xfbbad70 {name = TestNotification; userInfo = {0} {0} {0} TestData =“一些数据”; }}

如果我发布没有userInfo对象的通知(只是零),测试工作。有人可以解释为什么吗?

+0

这是一个构造得很好的问题。它只花了我几秒钟的时间用您发布的代码重新创建您的问题。 –

回答

8

当您未指定userInfo时,它预计为零。将其更改为:

[[observerMock expect] notificationWithName:@"TestNotification" object:[OCMArg any] userInfo:[OCMArg any]]; 

它应该通过。

+0

完美!谢谢。 – sash