Question

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

Unit test:

-(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];
}

I get error:

OCMockObserver: unexpected notification observed: NSConcreteNotification 0xfbbad70 {name = TestNotification; userInfo = { TestData = "Some data"; }}

If I post notification without userInfo object (just nil), test works. Can someone please explain why?

Was it helpful?

Solution

When you don't specify userInfo it expects nil for the value. Change it to:

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

It should pass.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top