3

通知管理器.h

#import <Foundation/Foundation.h>

@interface NotificationManager : NSObject

-(void)postNotification;

@end

通知管理器.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),则测试有效。有人可以解释为什么吗?

4

1 回答 1

9

当您未指定userInfo时,它期望值为零。将其更改为:

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

它应该通过。

于 2013-12-20T00:41:06.940 回答