NotificationManager.h
#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 = { TestData =“一些数据”; }}
如果我发布没有userInfo对象的通知(只是nil),测试工作。有人可以解释一下原因吗?
答案 0 :(得分:9)
如果未指定userInfo
,则预计值为nil。将其更改为:
[[observerMock expect] notificationWithName:@"TestNotification" object:[OCMArg any] userInfo:[OCMArg any]];
它应该通过。