objective-cunit-testingocmock

OCMock notification observer - verifying the object


I've recently started working with OCMock framework and trying to figure out how to use the notification observer. So in my source code I'm observing some notification:

typedef enum {
  OperationStatusCompleted,
  // Some other statuses
} SomeOperationStatus;

- (void)addObserverForSomeNotification {
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(someOperationStatusDidChange:)
                                               name:@"someOperationStatusDidChange"
                                             object:nil];

- (void)backgroundOperationStatusDidChange:(NSNotification *)notification {
  id<SomeOperationProtocol> operation = [notification object];
  if (operation.status == OperationStatusCompleted) {
    // Do something.
  }
}

Now I want to add the expectation for that notification in my test:

- (void)testNotification {
  id observerMock = OCMObserverMock();
  [[NSNotificationCenter defaultCenter] addMockObserver:observerMock name:@"someOperationStatusChanged" object:nil];
  [[observerMock expect] notificationWithName:@"someOperationStatusChanged" object:[OCMArg any]];
   // run the test ...
}

That by itself works fine and I'm receiving the notification in the test but what I actually want to check is the status of the object of the notification (meaning that I've received a notification with specific object with specific status). Is it possible?


Solution

  • I finally figured out how to do it:

    [[observerMock expect] notificationWithName:@"someOperationStatusChanged" object:[OCMArg checkWithBlock:^BOOL(id<IMBBackgroundOperation> param) { 
        return param.status == OperationStatusCompleted;
    }]];